Revert "make reciprocal estimate code generation more flexible by adding command...
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 static cl::opt<int> ReciprocalEstimateRefinementSteps(
71     "x86-recip-refinement-steps", cl::init(1),
72     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
73              "result of the hardware reciprocal estimate instruction."),
74     cl::NotHidden);
75
76 // Forward declarations.
77 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
78                        SDValue V2);
79
80 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
81                                      const X86Subtarget &STI)
82     : TargetLowering(TM), Subtarget(&STI) {
83   X86ScalarSSEf64 = Subtarget->hasSSE2();
84   X86ScalarSSEf32 = Subtarget->hasSSE1();
85   TD = getDataLayout();
86
87   // Set up the TargetLowering object.
88   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
89
90   // X86 is weird. It always uses i8 for shift amounts and setcc results.
91   setBooleanContents(ZeroOrOneBooleanContent);
92   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
93   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
94
95   // For 64-bit, since we have so many registers, use the ILP scheduler.
96   // For 32-bit, use the register pressure specific scheduling.
97   // For Atom, always use ILP scheduling.
98   if (Subtarget->isAtom())
99     setSchedulingPreference(Sched::ILP);
100   else if (Subtarget->is64Bit())
101     setSchedulingPreference(Sched::ILP);
102   else
103     setSchedulingPreference(Sched::RegPressure);
104   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
105   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
106
107   // Bypass expensive divides on Atom when compiling with O2.
108   if (TM.getOptLevel() >= CodeGenOpt::Default) {
109     if (Subtarget->hasSlowDivide32())
110       addBypassSlowDiv(32, 8);
111     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
112       addBypassSlowDiv(64, 16);
113   }
114
115   if (Subtarget->isTargetKnownWindowsMSVC()) {
116     // Setup Windows compiler runtime calls.
117     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
118     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
119     setLibcallName(RTLIB::SREM_I64, "_allrem");
120     setLibcallName(RTLIB::UREM_I64, "_aullrem");
121     setLibcallName(RTLIB::MUL_I64, "_allmul");
122     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
123     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
124     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
125     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
126     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
127
128     // The _ftol2 runtime function has an unusual calling conv, which
129     // is modeled by a special pseudo-instruction.
130     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
131     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
132     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
133     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
134   }
135
136   if (Subtarget->isTargetDarwin()) {
137     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
138     setUseUnderscoreSetJmp(false);
139     setUseUnderscoreLongJmp(false);
140   } else if (Subtarget->isTargetWindowsGNU()) {
141     // MS runtime is weird: it exports _setjmp, but longjmp!
142     setUseUnderscoreSetJmp(true);
143     setUseUnderscoreLongJmp(false);
144   } else {
145     setUseUnderscoreSetJmp(true);
146     setUseUnderscoreLongJmp(true);
147   }
148
149   // Set up the register classes.
150   addRegisterClass(MVT::i8, &X86::GR8RegClass);
151   addRegisterClass(MVT::i16, &X86::GR16RegClass);
152   addRegisterClass(MVT::i32, &X86::GR32RegClass);
153   if (Subtarget->is64Bit())
154     addRegisterClass(MVT::i64, &X86::GR64RegClass);
155
156   for (MVT VT : MVT::integer_valuetypes())
157     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
158
159   // We don't accept any truncstore of integer registers.
160   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
161   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
162   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
163   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
164   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
165   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
166
167   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
168
169   // SETOEQ and SETUNE require checking two conditions.
170   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
171   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
172   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
173   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
174   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
175   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
176
177   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
178   // operation.
179   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
180   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
181   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
182
183   if (Subtarget->is64Bit()) {
184     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
185     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
186   } else if (!Subtarget->useSoftFloat()) {
187     // We have an algorithm for SSE2->double, and we turn this into a
188     // 64-bit FILD followed by conditional FADD for other targets.
189     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
190     // We have an algorithm for SSE2, and we turn this into a 64-bit
191     // FILD for other targets.
192     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
193   }
194
195   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
196   // this operation.
197   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
198   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
199
200   if (!Subtarget->useSoftFloat()) {
201     // SSE has no i16 to fp conversion, only i32
202     if (X86ScalarSSEf32) {
203       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
204       // f32 and f64 cases are Legal, f80 case is not
205       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
206     } else {
207       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
208       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
209     }
210   } else {
211     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
212     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
213   }
214
215   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
216   // are Legal, f80 is custom lowered.
217   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
218   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
219
220   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
221   // this operation.
222   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
223   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
224
225   if (X86ScalarSSEf32) {
226     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
227     // f32 and f64 cases are Legal, f80 case is not
228     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
229   } else {
230     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
231     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
232   }
233
234   // Handle FP_TO_UINT by promoting the destination to a larger signed
235   // conversion.
236   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
237   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
238   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
239
240   if (Subtarget->is64Bit()) {
241     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
242     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
243   } else if (!Subtarget->useSoftFloat()) {
244     // Since AVX is a superset of SSE3, only check for SSE here.
245     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246       // Expand FP_TO_UINT into a select.
247       // FIXME: We would like to use a Custom expander here eventually to do
248       // the optimal thing for SSE vs. the default expansion in the legalizer.
249       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
250     else
251       // With SSE3 we can use fisttpll to convert to a signed i64; without
252       // SSE, we're stuck with a fistpll.
253       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
254   }
255
256   if (isTargetFTOL()) {
257     // Use the _ftol2 runtime function, which has a pseudo-instruction
258     // to handle its weird calling convention.
259     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
260   }
261
262   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
263   if (!X86ScalarSSEf64) {
264     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
265     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
266     if (Subtarget->is64Bit()) {
267       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
268       // Without SSE, i64->f64 goes through memory.
269       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
270     }
271   }
272
273   // Scalar integer divide and remainder are lowered to use operations that
274   // produce two results, to match the available instructions. This exposes
275   // the two-result form to trivial CSE, which is able to combine x/y and x%y
276   // into a single instruction.
277   //
278   // Scalar integer multiply-high is also lowered to use two-result
279   // operations, to match the available instructions. However, plain multiply
280   // (low) operations are left as Legal, as there are single-result
281   // instructions for this in x86. Using the two-result multiply instructions
282   // when both high and low results are needed must be arranged by dagcombine.
283   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
284     MVT VT = IntVTs[i];
285     setOperationAction(ISD::MULHS, VT, Expand);
286     setOperationAction(ISD::MULHU, VT, Expand);
287     setOperationAction(ISD::SDIV, VT, Expand);
288     setOperationAction(ISD::UDIV, VT, Expand);
289     setOperationAction(ISD::SREM, VT, Expand);
290     setOperationAction(ISD::UREM, VT, Expand);
291
292     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
293     setOperationAction(ISD::ADDC, VT, Custom);
294     setOperationAction(ISD::ADDE, VT, Custom);
295     setOperationAction(ISD::SUBC, VT, Custom);
296     setOperationAction(ISD::SUBE, VT, Custom);
297   }
298
299   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
300   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
301   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
302   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
303   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
305   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
306   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
307   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
313   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
314   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
315   if (Subtarget->is64Bit())
316     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
318   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
319   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
320   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
321   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
322   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
323   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
324   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
325
326   // Promote the i8 variants and force them on up to i32 which has a shorter
327   // encoding.
328   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
329   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
330   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
331   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
332   if (Subtarget->hasBMI()) {
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
334     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
335     if (Subtarget->is64Bit())
336       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
337   } else {
338     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
339     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
342   }
343
344   if (Subtarget->hasLZCNT()) {
345     // When promoting the i8 variants, force them to i32 for a shorter
346     // encoding.
347     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
348     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
350     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
352     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
353     if (Subtarget->is64Bit())
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
355   } else {
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
357     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
358     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
364       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
365     }
366   }
367
368   // Special handling for half-precision floating point conversions.
369   // If we don't have F16C support, then lower half float conversions
370   // into library calls.
371   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
372     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
374   }
375
376   // There's never any support for operations beyond MVT::f32.
377   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
381
382   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400
401   if (!Subtarget->hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403
404   // These should be promoted to a larger select which is supported.
405   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
406   // X86 wants to expand cmov itself.
407   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
421     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
422   }
423   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
424   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426   // support continuation, user-level threading, and etc.. As a result, no
427   // other SjLj exception interfaces are implemented and please don't build
428   // your own exception handling based on them.
429   // LLVM/Clang supports zero-cost DWARF exception handling.
430   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
432
433   // Darwin ABI issue.
434   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
435   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
437   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
438   if (Subtarget->is64Bit())
439     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
441   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
442   if (Subtarget->is64Bit()) {
443     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
444     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
445     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
446     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
447     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
448   }
449   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
452   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
456     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
457   }
458
459   if (Subtarget->hasSSE1())
460     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
461
462   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
463
464   // Expand certain atomics
465   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
466     MVT VT = IntVTs[i];
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470   }
471
472   if (Subtarget->hasCmpxchg16b()) {
473     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
474   }
475
476   // FIXME - use subtarget debug flags
477   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481
482   if (Subtarget->is64Bit()) {
483     setExceptionPointerRegister(X86::RAX);
484     setExceptionSelectorRegister(X86::RDX);
485   } else {
486     setExceptionPointerRegister(X86::EAX);
487     setExceptionSelectorRegister(X86::EDX);
488   }
489   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
491
492   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
494
495   setOperationAction(ISD::TRAP, MVT::Other, Legal);
496   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
497
498   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
500   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
501   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
502     // TargetInfo::X86_64ABIBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
505   } else {
506     // TargetInfo::CharPtrBuiltinVaList
507     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
508     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
509   }
510
511   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
512   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
513
514   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
515
516   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
518   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
519
520   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
521     // f32 and f64 use SSE.
522     // Set up the FP register classes.
523     addRegisterClass(MVT::f32, &X86::FR32RegClass);
524     addRegisterClass(MVT::f64, &X86::FR64RegClass);
525
526     // Use ANDPD to simulate FABS.
527     setOperationAction(ISD::FABS , MVT::f64, Custom);
528     setOperationAction(ISD::FABS , MVT::f32, Custom);
529
530     // Use XORP to simulate FNEG.
531     setOperationAction(ISD::FNEG , MVT::f64, Custom);
532     setOperationAction(ISD::FNEG , MVT::f32, Custom);
533
534     // Use ANDPD and ORPD to simulate FCOPYSIGN.
535     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
536     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
537
538     // Lower this to FGETSIGNx86 plus an AND.
539     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
540     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
541
542     // We don't support sin/cos/fmod
543     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
544     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
546     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
547     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
548     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
549
550     // Expand FP immediates into loads from the stack, except for the special
551     // cases we handle.
552     addLegalFPImmediate(APFloat(+0.0)); // xorpd
553     addLegalFPImmediate(APFloat(+0.0f)); // xorps
554   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
555     // Use SSE for f32, x87 for f64.
556     // Set up the FP register classes.
557     addRegisterClass(MVT::f32, &X86::FR32RegClass);
558     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559
560     // Use ANDPS to simulate FABS.
561     setOperationAction(ISD::FABS , MVT::f32, Custom);
562
563     // Use XORP to simulate FNEG.
564     setOperationAction(ISD::FNEG , MVT::f32, Custom);
565
566     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
567
568     // Use ANDPS and ORPS to simulate FCOPYSIGN.
569     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
570     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571
572     // We don't support sin/cos/fmod
573     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
575     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
576
577     // Special cases we handle for FP constants.
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579     addLegalFPImmediate(APFloat(+0.0)); // FLD0
580     addLegalFPImmediate(APFloat(+1.0)); // FLD1
581     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583
584     if (!TM.Options.UnsafeFPMath) {
585       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
586       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
587       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588     }
589   } else if (!Subtarget->useSoftFloat()) {
590     // f32 and f64 in x87.
591     // Set up the FP register classes.
592     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594
595     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
596     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
599
600     if (!TM.Options.UnsafeFPMath) {
601       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
602       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
603       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
604       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
605       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
606       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
607     }
608     addLegalFPImmediate(APFloat(+0.0)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
613     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
614     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
615     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
616   }
617
618   // We don't support FMA.
619   setOperationAction(ISD::FMA, MVT::f64, Expand);
620   setOperationAction(ISD::FMA, MVT::f32, Expand);
621
622   // Long double always uses X87.
623   if (!Subtarget->useSoftFloat()) {
624     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
626     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
627     {
628       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
629       addLegalFPImmediate(TmpFlt);  // FLD0
630       TmpFlt.changeSign();
631       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
632
633       bool ignored;
634       APFloat TmpFlt2(+1.0);
635       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
636                       &ignored);
637       addLegalFPImmediate(TmpFlt2);  // FLD1
638       TmpFlt2.changeSign();
639       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
640     }
641
642     if (!TM.Options.UnsafeFPMath) {
643       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
644       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
645       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
646     }
647
648     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
649     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
650     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
651     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
652     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
653     setOperationAction(ISD::FMA, MVT::f80, Expand);
654   }
655
656   // Always use a library call for pow.
657   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
658   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
659   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
660
661   setOperationAction(ISD::FLOG, MVT::f80, Expand);
662   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
663   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
664   setOperationAction(ISD::FEXP, MVT::f80, Expand);
665   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
666   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
667   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
668
669   // First set operation action for all vector types to either promote
670   // (for widening) or expand (for scalarization). Then we will selectively
671   // turn on ones that can be effectively codegen'd.
672   for (MVT VT : MVT::vector_valuetypes()) {
673     setOperationAction(ISD::ADD , VT, Expand);
674     setOperationAction(ISD::SUB , VT, Expand);
675     setOperationAction(ISD::FADD, VT, Expand);
676     setOperationAction(ISD::FNEG, VT, Expand);
677     setOperationAction(ISD::FSUB, VT, Expand);
678     setOperationAction(ISD::MUL , VT, Expand);
679     setOperationAction(ISD::FMUL, VT, Expand);
680     setOperationAction(ISD::SDIV, VT, Expand);
681     setOperationAction(ISD::UDIV, VT, Expand);
682     setOperationAction(ISD::FDIV, VT, Expand);
683     setOperationAction(ISD::SREM, VT, Expand);
684     setOperationAction(ISD::UREM, VT, Expand);
685     setOperationAction(ISD::LOAD, VT, Expand);
686     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
687     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
688     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
689     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
690     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
691     setOperationAction(ISD::FABS, VT, Expand);
692     setOperationAction(ISD::FSIN, VT, Expand);
693     setOperationAction(ISD::FSINCOS, VT, Expand);
694     setOperationAction(ISD::FCOS, VT, Expand);
695     setOperationAction(ISD::FSINCOS, VT, Expand);
696     setOperationAction(ISD::FREM, VT, Expand);
697     setOperationAction(ISD::FMA,  VT, Expand);
698     setOperationAction(ISD::FPOWI, VT, Expand);
699     setOperationAction(ISD::FSQRT, VT, Expand);
700     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
701     setOperationAction(ISD::FFLOOR, VT, Expand);
702     setOperationAction(ISD::FCEIL, VT, Expand);
703     setOperationAction(ISD::FTRUNC, VT, Expand);
704     setOperationAction(ISD::FRINT, VT, Expand);
705     setOperationAction(ISD::FNEARBYINT, VT, Expand);
706     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
707     setOperationAction(ISD::MULHS, VT, Expand);
708     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
709     setOperationAction(ISD::MULHU, VT, Expand);
710     setOperationAction(ISD::SDIVREM, VT, Expand);
711     setOperationAction(ISD::UDIVREM, VT, Expand);
712     setOperationAction(ISD::FPOW, VT, Expand);
713     setOperationAction(ISD::CTPOP, VT, Expand);
714     setOperationAction(ISD::CTTZ, VT, Expand);
715     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
716     setOperationAction(ISD::CTLZ, VT, Expand);
717     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
718     setOperationAction(ISD::SHL, VT, Expand);
719     setOperationAction(ISD::SRA, VT, Expand);
720     setOperationAction(ISD::SRL, VT, Expand);
721     setOperationAction(ISD::ROTL, VT, Expand);
722     setOperationAction(ISD::ROTR, VT, Expand);
723     setOperationAction(ISD::BSWAP, VT, Expand);
724     setOperationAction(ISD::SETCC, VT, Expand);
725     setOperationAction(ISD::FLOG, VT, Expand);
726     setOperationAction(ISD::FLOG2, VT, Expand);
727     setOperationAction(ISD::FLOG10, VT, Expand);
728     setOperationAction(ISD::FEXP, VT, Expand);
729     setOperationAction(ISD::FEXP2, VT, Expand);
730     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
731     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
732     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
733     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
735     setOperationAction(ISD::TRUNCATE, VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
737     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
738     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
739     setOperationAction(ISD::VSELECT, VT, Expand);
740     setOperationAction(ISD::SELECT_CC, VT, Expand);
741     for (MVT InnerVT : MVT::vector_valuetypes()) {
742       setTruncStoreAction(InnerVT, VT, Expand);
743
744       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
745       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
746
747       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
748       // types, we have to deal with them whether we ask for Expansion or not.
749       // Setting Expand causes its own optimisation problems though, so leave
750       // them legal.
751       if (VT.getVectorElementType() == MVT::i1)
752         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753
754       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
755       // split/scalarized right now.
756       if (VT.getVectorElementType() == MVT::f16)
757         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
758     }
759   }
760
761   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
762   // with -msoft-float, disable use of MMX as well.
763   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
764     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
765     // No operations on x86mmx supported, everything uses intrinsics.
766   }
767
768   // MMX-sized vectors (other than x86mmx) are expected to be expanded
769   // into smaller operations.
770   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
771     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
772     setOperationAction(ISD::AND,                MMXTy,      Expand);
773     setOperationAction(ISD::OR,                 MMXTy,      Expand);
774     setOperationAction(ISD::XOR,                MMXTy,      Expand);
775     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
776     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
777     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
778   }
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780
781   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
782     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
783
784     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
788     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
789     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
790     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
791     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
792     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
793     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
794     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
795     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
796     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
797     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
798   }
799
800   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
801     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
802
803     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
804     // registers cannot be used even for integer operations.
805     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
806     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
807     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
808     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
809
810     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
811     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
812     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
813     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
814     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
815     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
816     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
817     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
818     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
819     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
820     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
833
834     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
838
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
840     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
844
845     // Only provide customized ctpop vector bit twiddling for vector types we
846     // know to perform better than using the popcnt instructions on each vector
847     // element. If popcnt isn't supported, always provide the custom version.
848     if (!Subtarget->hasPOPCNT()) {
849       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
850       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
851     }
852
853     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
854     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
855       MVT VT = (MVT::SimpleValueType)i;
856       // Do not attempt to custom lower non-power-of-2 vectors
857       if (!isPowerOf2_32(VT.getVectorNumElements()))
858         continue;
859       // Do not attempt to custom lower non-128-bit vectors
860       if (!VT.is128BitVector())
861         continue;
862       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
863       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
864       setOperationAction(ISD::VSELECT,            VT, Custom);
865       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
866     }
867
868     // We support custom legalizing of sext and anyext loads for specific
869     // memory vector types which we can load as a scalar (or sequence of
870     // scalars) and extend in-register to a legal 128-bit vector type. For sext
871     // loads these must work with a single scalar load.
872     for (MVT VT : MVT::integer_vector_valuetypes()) {
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
874       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
875       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
880       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
881       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
882     }
883
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
885     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
887     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
888     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
889     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
891     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
892
893     if (Subtarget->is64Bit()) {
894       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
895       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
896     }
897
898     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900       MVT VT = (MVT::SimpleValueType)i;
901
902       // Do not attempt to promote non-128-bit vectors
903       if (!VT.is128BitVector())
904         continue;
905
906       setOperationAction(ISD::AND,    VT, Promote);
907       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
908       setOperationAction(ISD::OR,     VT, Promote);
909       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
910       setOperationAction(ISD::XOR,    VT, Promote);
911       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
912       setOperationAction(ISD::LOAD,   VT, Promote);
913       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
914       setOperationAction(ISD::SELECT, VT, Promote);
915       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
916     }
917
918     // Custom lower v2i64 and v2f64 selects.
919     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
920     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
921     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
922     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
923
924     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
925     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
926
927     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
928     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
929     // As there is no 64-bit GPR available, we need build a special custom
930     // sequence to convert from v2i32 to v2f32.
931     if (!Subtarget->is64Bit())
932       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
933
934     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
935     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
936
937     for (MVT VT : MVT::fp_vector_valuetypes())
938       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
939
940     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
941     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
942     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
943   }
944
945   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
948       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
949       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
950       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
951       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
952     }
953
954     // FIXME: Do we need to handle scalar-to-vector here?
955     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
956
957     // We directly match byte blends in the backend as they match the VSELECT
958     // condition form.
959     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
960
961     // SSE41 brings specific instructions for doing vector sign extend even in
962     // cases where we don't have SRA.
963     for (MVT VT : MVT::integer_vector_valuetypes()) {
964       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
965       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
966       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
967     }
968
969     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
970     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
971     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
972     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
973     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
974     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
975     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
976
977     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     // i8 and i16 vectors are custom because the source register and source
985     // source memory operand types are not the same width.  f32 vectors are
986     // custom since the immediate controlling the insert encodes additional
987     // information.
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
990     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
992
993     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
994     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
995     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
996     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
997
998     // FIXME: these should be Legal, but that's only for the case where
999     // the index is constant.  For now custom expand to deal with that.
1000     if (Subtarget->is64Bit()) {
1001       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1002       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003     }
1004   }
1005
1006   if (Subtarget->hasSSE2()) {
1007     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1008     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1009     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1010
1011     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1012     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1013
1014     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1015     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1016
1017     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1018     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1019
1020     // In the customized shift lowering, the legal cases in AVX2 will be
1021     // recognized.
1022     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1023     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1024
1025     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1026     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1027
1028     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1029   }
1030
1031   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1032     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1033     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1034     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1035     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1036     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1038
1039     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1041     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1042
1043     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1045     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1046     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1047     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1048     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1049     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1050     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1051     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1052     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1053     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1054     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1055
1056     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1057     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1058     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1059     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1060     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1061     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1062     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1063     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1064     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1065     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1066     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1067     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1068
1069     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1070     // even though v8i16 is a legal type.
1071     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1072     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1073     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1074
1075     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1076     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1077     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1078
1079     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1080     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1081
1082     for (MVT VT : MVT::fp_vector_valuetypes())
1083       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1084
1085     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1086     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1087
1088     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1089     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1090
1091     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1092     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1093
1094     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1095     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1096     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1097     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1098
1099     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1100     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1101     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1102
1103     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1104     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1105     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1106     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1107     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1108     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1109     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1110     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1111     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1112     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1113     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1114     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1115
1116     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1117       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1118       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1119       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1120       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1121       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1122       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1123     }
1124
1125     if (Subtarget->hasInt256()) {
1126       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1127       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1128       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1129       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1130
1131       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1132       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1133       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1134       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1135
1136       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1137       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1138       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1139       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1140
1141       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1142       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1143       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1144       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1145
1146       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1147       // when we have a 256bit-wide blend with immediate.
1148       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1149
1150       // Only provide customized ctpop vector bit twiddling for vector types we
1151       // know to perform better than using the popcnt instructions on each
1152       // vector element. If popcnt isn't supported, always provide the custom
1153       // version.
1154       if (!Subtarget->hasPOPCNT())
1155         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1156
1157       // Custom CTPOP always performs better on natively supported v8i32
1158       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1159
1160       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1161       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1162       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1163       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1164       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1165       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1166       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1167
1168       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1169       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1170       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1171       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1172       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1173       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1174     } else {
1175       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1176       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1177       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1178       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1179
1180       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1181       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1182       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1183       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1184
1185       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1186       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1187       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1188       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1189     }
1190
1191     // In the customized shift lowering, the legal cases in AVX2 will be
1192     // recognized.
1193     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1194     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1195
1196     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1197     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1198
1199     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1200
1201     // Custom lower several nodes for 256-bit types.
1202     for (MVT VT : MVT::vector_valuetypes()) {
1203       if (VT.getScalarSizeInBits() >= 32) {
1204         setOperationAction(ISD::MLOAD,  VT, Legal);
1205         setOperationAction(ISD::MSTORE, VT, Legal);
1206       }
1207       // Extract subvector is special because the value type
1208       // (result) is 128-bit but the source is 256-bit wide.
1209       if (VT.is128BitVector()) {
1210         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1211       }
1212       // Do not attempt to custom lower other non-256-bit vectors
1213       if (!VT.is256BitVector())
1214         continue;
1215
1216       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1217       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1218       setOperationAction(ISD::VSELECT,            VT, Custom);
1219       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1220       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1221       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1222       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1223       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1224     }
1225
1226     if (Subtarget->hasInt256())
1227       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1228
1229
1230     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1231     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1232       MVT VT = (MVT::SimpleValueType)i;
1233
1234       // Do not attempt to promote non-256-bit vectors
1235       if (!VT.is256BitVector())
1236         continue;
1237
1238       setOperationAction(ISD::AND,    VT, Promote);
1239       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1240       setOperationAction(ISD::OR,     VT, Promote);
1241       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1242       setOperationAction(ISD::XOR,    VT, Promote);
1243       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1244       setOperationAction(ISD::LOAD,   VT, Promote);
1245       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1246       setOperationAction(ISD::SELECT, VT, Promote);
1247       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1248     }
1249   }
1250
1251   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1252     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1253     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1254     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1255     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1256
1257     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1258     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1259     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1260
1261     for (MVT VT : MVT::fp_vector_valuetypes())
1262       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1263
1264     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1265     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1266     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1267     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1268     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1269     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1270     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1271     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1272     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1273     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1274
1275     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1276     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1277     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1278     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1279     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1280     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1281
1282     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1283     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1284     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1285     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1286     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1287     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1288     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1289     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1290
1291     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1292     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1293     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1294     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1295     if (Subtarget->is64Bit()) {
1296       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1297       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1298       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1299       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1300     }
1301     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1302     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1303     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1304     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1305     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1306     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1307     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1308     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1309     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1310     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1311     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1312     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1313     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1314     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1315     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1316     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1317
1318     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1319     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1320     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1321     if (Subtarget->hasDQI()) {
1322       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1323       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1324     }
1325     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1326     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1327     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1328     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1329     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1330     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1331     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1332     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1333     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1334     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1335     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1336     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1337     if (Subtarget->hasDQI()) {
1338       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1339       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1340     }
1341     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1342     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1343     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1344     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1345     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1346     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1347     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1348     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1349     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1350     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1351
1352     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1353     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1354     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1355     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1356     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1357
1358     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1359     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1360
1361     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1362
1363     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1364     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1365     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1366     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1367     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1368     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1369     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1370     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1371     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1372     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1373     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1374
1375     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1376     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1377
1378     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1379     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1380
1381     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1382
1383     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1384     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1385
1386     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1387     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1388
1389     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1390     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1391
1392     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1393     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1394     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1395     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1396     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1397     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1398
1399     if (Subtarget->hasCDI()) {
1400       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1401       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1402     }
1403     if (Subtarget->hasDQI()) {
1404       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1405       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1406       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1407     }
1408     // Custom lower several nodes.
1409     for (MVT VT : MVT::vector_valuetypes()) {
1410       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1411       if (EltSize == 1) {
1412         setOperationAction(ISD::AND, VT, Legal);
1413         setOperationAction(ISD::OR,  VT, Legal);
1414         setOperationAction(ISD::XOR,  VT, Legal);
1415       }
1416       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1417         setOperationAction(ISD::MGATHER,  VT, Custom);
1418         setOperationAction(ISD::MSCATTER, VT, Custom);
1419       }
1420       // Extract subvector is special because the value type
1421       // (result) is 256/128-bit but the source is 512-bit wide.
1422       if (VT.is128BitVector() || VT.is256BitVector()) {
1423         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1424       }
1425       if (VT.getVectorElementType() == MVT::i1)
1426         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1427
1428       // Do not attempt to custom lower other non-512-bit vectors
1429       if (!VT.is512BitVector())
1430         continue;
1431
1432       if (EltSize >= 32) {
1433         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1434         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1435         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1436         setOperationAction(ISD::VSELECT,             VT, Legal);
1437         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1438         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1439         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1440         setOperationAction(ISD::MLOAD,               VT, Legal);
1441         setOperationAction(ISD::MSTORE,              VT, Legal);
1442       }
1443     }
1444     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1445       MVT VT = (MVT::SimpleValueType)i;
1446
1447       // Do not attempt to promote non-512-bit vectors.
1448       if (!VT.is512BitVector())
1449         continue;
1450
1451       setOperationAction(ISD::SELECT, VT, Promote);
1452       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1453     }
1454   }// has  AVX-512
1455
1456   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1457     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1458     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1459
1460     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1461     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1462
1463     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1464     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1465     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1466     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1467     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1468     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1469     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1470     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1471     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1472     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1473     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1474     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1475     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1476     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1477     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1478     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1479     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1480     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1481     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1482
1483     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1484       const MVT VT = (MVT::SimpleValueType)i;
1485
1486       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1487
1488       // Do not attempt to promote non-512-bit vectors.
1489       if (!VT.is512BitVector())
1490         continue;
1491
1492       if (EltSize < 32) {
1493         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1494         setOperationAction(ISD::VSELECT,             VT, Legal);
1495       }
1496     }
1497   }
1498
1499   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1500     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1501     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1502
1503     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1504     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1505     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1506     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1507     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1508     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1509     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1510     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1511     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1512     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1513
1514     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1515     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1516     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1517     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1518     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1519     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1520     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1521     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1522   }
1523
1524   // We want to custom lower some of our intrinsics.
1525   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1526   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1527   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1528   if (!Subtarget->is64Bit())
1529     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1530
1531   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1532   // handle type legalization for these operations here.
1533   //
1534   // FIXME: We really should do custom legalization for addition and
1535   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1536   // than generic legalization for 64-bit multiplication-with-overflow, though.
1537   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1538     // Add/Sub/Mul with overflow operations are custom lowered.
1539     MVT VT = IntVTs[i];
1540     setOperationAction(ISD::SADDO, VT, Custom);
1541     setOperationAction(ISD::UADDO, VT, Custom);
1542     setOperationAction(ISD::SSUBO, VT, Custom);
1543     setOperationAction(ISD::USUBO, VT, Custom);
1544     setOperationAction(ISD::SMULO, VT, Custom);
1545     setOperationAction(ISD::UMULO, VT, Custom);
1546   }
1547
1548
1549   if (!Subtarget->is64Bit()) {
1550     // These libcalls are not available in 32-bit.
1551     setLibcallName(RTLIB::SHL_I128, nullptr);
1552     setLibcallName(RTLIB::SRL_I128, nullptr);
1553     setLibcallName(RTLIB::SRA_I128, nullptr);
1554   }
1555
1556   // Combine sin / cos into one node or libcall if possible.
1557   if (Subtarget->hasSinCos()) {
1558     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1559     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1560     if (Subtarget->isTargetDarwin()) {
1561       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1562       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1563       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1564       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1565     }
1566   }
1567
1568   if (Subtarget->isTargetWin64()) {
1569     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1570     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1571     setOperationAction(ISD::SREM, MVT::i128, Custom);
1572     setOperationAction(ISD::UREM, MVT::i128, Custom);
1573     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1574     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1575   }
1576
1577   // We have target-specific dag combine patterns for the following nodes:
1578   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1579   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1580   setTargetDAGCombine(ISD::BITCAST);
1581   setTargetDAGCombine(ISD::VSELECT);
1582   setTargetDAGCombine(ISD::SELECT);
1583   setTargetDAGCombine(ISD::SHL);
1584   setTargetDAGCombine(ISD::SRA);
1585   setTargetDAGCombine(ISD::SRL);
1586   setTargetDAGCombine(ISD::OR);
1587   setTargetDAGCombine(ISD::AND);
1588   setTargetDAGCombine(ISD::ADD);
1589   setTargetDAGCombine(ISD::FADD);
1590   setTargetDAGCombine(ISD::FSUB);
1591   setTargetDAGCombine(ISD::FMA);
1592   setTargetDAGCombine(ISD::SUB);
1593   setTargetDAGCombine(ISD::LOAD);
1594   setTargetDAGCombine(ISD::MLOAD);
1595   setTargetDAGCombine(ISD::STORE);
1596   setTargetDAGCombine(ISD::MSTORE);
1597   setTargetDAGCombine(ISD::ZERO_EXTEND);
1598   setTargetDAGCombine(ISD::ANY_EXTEND);
1599   setTargetDAGCombine(ISD::SIGN_EXTEND);
1600   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1601   setTargetDAGCombine(ISD::SINT_TO_FP);
1602   setTargetDAGCombine(ISD::SETCC);
1603   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1604   setTargetDAGCombine(ISD::BUILD_VECTOR);
1605   setTargetDAGCombine(ISD::MUL);
1606   setTargetDAGCombine(ISD::XOR);
1607
1608   computeRegisterProperties(Subtarget->getRegisterInfo());
1609
1610   // On Darwin, -Os means optimize for size without hurting performance,
1611   // do not reduce the limit.
1612   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1613   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1614   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1615   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1616   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1617   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1618   setPrefLoopAlignment(4); // 2^4 bytes.
1619
1620   // Predictable cmov don't hurt on atom because it's in-order.
1621   PredictableSelectIsExpensive = !Subtarget->isAtom();
1622   EnableExtLdPromotion = true;
1623   setPrefFunctionAlignment(4); // 2^4 bytes.
1624
1625   verifyIntrinsicTables();
1626 }
1627
1628 // This has so far only been implemented for 64-bit MachO.
1629 bool X86TargetLowering::useLoadStackGuardNode() const {
1630   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1631 }
1632
1633 TargetLoweringBase::LegalizeTypeAction
1634 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1635   if (ExperimentalVectorWideningLegalization &&
1636       VT.getVectorNumElements() != 1 &&
1637       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1638     return TypeWidenVector;
1639
1640   return TargetLoweringBase::getPreferredVectorAction(VT);
1641 }
1642
1643 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1644   if (!VT.isVector())
1645     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1646
1647   const unsigned NumElts = VT.getVectorNumElements();
1648   const EVT EltVT = VT.getVectorElementType();
1649   if (VT.is512BitVector()) {
1650     if (Subtarget->hasAVX512())
1651       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1652           EltVT == MVT::f32 || EltVT == MVT::f64)
1653         switch(NumElts) {
1654         case  8: return MVT::v8i1;
1655         case 16: return MVT::v16i1;
1656       }
1657     if (Subtarget->hasBWI())
1658       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1659         switch(NumElts) {
1660         case 32: return MVT::v32i1;
1661         case 64: return MVT::v64i1;
1662       }
1663   }
1664
1665   if (VT.is256BitVector() || VT.is128BitVector()) {
1666     if (Subtarget->hasVLX())
1667       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1668           EltVT == MVT::f32 || EltVT == MVT::f64)
1669         switch(NumElts) {
1670         case 2: return MVT::v2i1;
1671         case 4: return MVT::v4i1;
1672         case 8: return MVT::v8i1;
1673       }
1674     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1675       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1676         switch(NumElts) {
1677         case  8: return MVT::v8i1;
1678         case 16: return MVT::v16i1;
1679         case 32: return MVT::v32i1;
1680       }
1681   }
1682
1683   return VT.changeVectorElementTypeToInteger();
1684 }
1685
1686 /// Helper for getByValTypeAlignment to determine
1687 /// the desired ByVal argument alignment.
1688 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1689   if (MaxAlign == 16)
1690     return;
1691   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1692     if (VTy->getBitWidth() == 128)
1693       MaxAlign = 16;
1694   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1695     unsigned EltAlign = 0;
1696     getMaxByValAlign(ATy->getElementType(), EltAlign);
1697     if (EltAlign > MaxAlign)
1698       MaxAlign = EltAlign;
1699   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1700     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1701       unsigned EltAlign = 0;
1702       getMaxByValAlign(STy->getElementType(i), EltAlign);
1703       if (EltAlign > MaxAlign)
1704         MaxAlign = EltAlign;
1705       if (MaxAlign == 16)
1706         break;
1707     }
1708   }
1709 }
1710
1711 /// Return the desired alignment for ByVal aggregate
1712 /// function arguments in the caller parameter area. For X86, aggregates
1713 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1714 /// are at 4-byte boundaries.
1715 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1716   if (Subtarget->is64Bit()) {
1717     // Max of 8 and alignment of type.
1718     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1719     if (TyAlign > 8)
1720       return TyAlign;
1721     return 8;
1722   }
1723
1724   unsigned Align = 4;
1725   if (Subtarget->hasSSE1())
1726     getMaxByValAlign(Ty, Align);
1727   return Align;
1728 }
1729
1730 /// Returns the target specific optimal type for load
1731 /// and store operations as a result of memset, memcpy, and memmove
1732 /// lowering. If DstAlign is zero that means it's safe to destination
1733 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1734 /// means there isn't a need to check it against alignment requirement,
1735 /// probably because the source does not need to be loaded. If 'IsMemset' is
1736 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1737 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1738 /// source is constant so it does not need to be loaded.
1739 /// It returns EVT::Other if the type should be determined using generic
1740 /// target-independent logic.
1741 EVT
1742 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1743                                        unsigned DstAlign, unsigned SrcAlign,
1744                                        bool IsMemset, bool ZeroMemset,
1745                                        bool MemcpyStrSrc,
1746                                        MachineFunction &MF) const {
1747   const Function *F = MF.getFunction();
1748   if ((!IsMemset || ZeroMemset) &&
1749       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1750     if (Size >= 16 &&
1751         (Subtarget->isUnalignedMemAccessFast() ||
1752          ((DstAlign == 0 || DstAlign >= 16) &&
1753           (SrcAlign == 0 || SrcAlign >= 16)))) {
1754       if (Size >= 32) {
1755         if (Subtarget->hasInt256())
1756           return MVT::v8i32;
1757         if (Subtarget->hasFp256())
1758           return MVT::v8f32;
1759       }
1760       if (Subtarget->hasSSE2())
1761         return MVT::v4i32;
1762       if (Subtarget->hasSSE1())
1763         return MVT::v4f32;
1764     } else if (!MemcpyStrSrc && Size >= 8 &&
1765                !Subtarget->is64Bit() &&
1766                Subtarget->hasSSE2()) {
1767       // Do not use f64 to lower memcpy if source is string constant. It's
1768       // better to use i32 to avoid the loads.
1769       return MVT::f64;
1770     }
1771   }
1772   if (Subtarget->is64Bit() && Size >= 8)
1773     return MVT::i64;
1774   return MVT::i32;
1775 }
1776
1777 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1778   if (VT == MVT::f32)
1779     return X86ScalarSSEf32;
1780   else if (VT == MVT::f64)
1781     return X86ScalarSSEf64;
1782   return true;
1783 }
1784
1785 bool
1786 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1787                                                   unsigned,
1788                                                   unsigned,
1789                                                   bool *Fast) const {
1790   if (Fast)
1791     *Fast = Subtarget->isUnalignedMemAccessFast();
1792   return true;
1793 }
1794
1795 /// Return the entry encoding for a jump table in the
1796 /// current function.  The returned value is a member of the
1797 /// MachineJumpTableInfo::JTEntryKind enum.
1798 unsigned X86TargetLowering::getJumpTableEncoding() const {
1799   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1800   // symbol.
1801   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1802       Subtarget->isPICStyleGOT())
1803     return MachineJumpTableInfo::EK_Custom32;
1804
1805   // Otherwise, use the normal jump table encoding heuristics.
1806   return TargetLowering::getJumpTableEncoding();
1807 }
1808
1809 bool X86TargetLowering::useSoftFloat() const {
1810   return Subtarget->useSoftFloat();
1811 }
1812
1813 const MCExpr *
1814 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1815                                              const MachineBasicBlock *MBB,
1816                                              unsigned uid,MCContext &Ctx) const{
1817   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1818          Subtarget->isPICStyleGOT());
1819   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1820   // entries.
1821   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1822                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1823 }
1824
1825 /// Returns relocation base for the given PIC jumptable.
1826 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1827                                                     SelectionDAG &DAG) const {
1828   if (!Subtarget->is64Bit())
1829     // This doesn't have SDLoc associated with it, but is not really the
1830     // same as a Register.
1831     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1832   return Table;
1833 }
1834
1835 /// This returns the relocation base for the given PIC jumptable,
1836 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1837 const MCExpr *X86TargetLowering::
1838 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1839                              MCContext &Ctx) const {
1840   // X86-64 uses RIP relative addressing based on the jump table label.
1841   if (Subtarget->isPICStyleRIPRel())
1842     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1843
1844   // Otherwise, the reference is relative to the PIC base.
1845   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1846 }
1847
1848 std::pair<const TargetRegisterClass *, uint8_t>
1849 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1850                                            MVT VT) const {
1851   const TargetRegisterClass *RRC = nullptr;
1852   uint8_t Cost = 1;
1853   switch (VT.SimpleTy) {
1854   default:
1855     return TargetLowering::findRepresentativeClass(TRI, VT);
1856   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1857     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1858     break;
1859   case MVT::x86mmx:
1860     RRC = &X86::VR64RegClass;
1861     break;
1862   case MVT::f32: case MVT::f64:
1863   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1864   case MVT::v4f32: case MVT::v2f64:
1865   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1866   case MVT::v4f64:
1867     RRC = &X86::VR128RegClass;
1868     break;
1869   }
1870   return std::make_pair(RRC, Cost);
1871 }
1872
1873 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1874                                                unsigned &Offset) const {
1875   if (!Subtarget->isTargetLinux())
1876     return false;
1877
1878   if (Subtarget->is64Bit()) {
1879     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1880     Offset = 0x28;
1881     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1882       AddressSpace = 256;
1883     else
1884       AddressSpace = 257;
1885   } else {
1886     // %gs:0x14 on i386
1887     Offset = 0x14;
1888     AddressSpace = 256;
1889   }
1890   return true;
1891 }
1892
1893 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1894                                             unsigned DestAS) const {
1895   assert(SrcAS != DestAS && "Expected different address spaces!");
1896
1897   return SrcAS < 256 && DestAS < 256;
1898 }
1899
1900 //===----------------------------------------------------------------------===//
1901 //               Return Value Calling Convention Implementation
1902 //===----------------------------------------------------------------------===//
1903
1904 #include "X86GenCallingConv.inc"
1905
1906 bool
1907 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1908                                   MachineFunction &MF, bool isVarArg,
1909                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1910                         LLVMContext &Context) const {
1911   SmallVector<CCValAssign, 16> RVLocs;
1912   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1913   return CCInfo.CheckReturn(Outs, RetCC_X86);
1914 }
1915
1916 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1917   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1918   return ScratchRegs;
1919 }
1920
1921 SDValue
1922 X86TargetLowering::LowerReturn(SDValue Chain,
1923                                CallingConv::ID CallConv, bool isVarArg,
1924                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1925                                const SmallVectorImpl<SDValue> &OutVals,
1926                                SDLoc dl, SelectionDAG &DAG) const {
1927   MachineFunction &MF = DAG.getMachineFunction();
1928   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1929
1930   SmallVector<CCValAssign, 16> RVLocs;
1931   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1932   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1933
1934   SDValue Flag;
1935   SmallVector<SDValue, 6> RetOps;
1936   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1937   // Operand #1 = Bytes To Pop
1938   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1939                    MVT::i16));
1940
1941   // Copy the result values into the output registers.
1942   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1943     CCValAssign &VA = RVLocs[i];
1944     assert(VA.isRegLoc() && "Can only return in registers!");
1945     SDValue ValToCopy = OutVals[i];
1946     EVT ValVT = ValToCopy.getValueType();
1947
1948     // Promote values to the appropriate types.
1949     if (VA.getLocInfo() == CCValAssign::SExt)
1950       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1951     else if (VA.getLocInfo() == CCValAssign::ZExt)
1952       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1953     else if (VA.getLocInfo() == CCValAssign::AExt) {
1954       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
1955         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1956       else
1957         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1958     }
1959     else if (VA.getLocInfo() == CCValAssign::BCvt)
1960       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1961
1962     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1963            "Unexpected FP-extend for return value.");
1964
1965     // If this is x86-64, and we disabled SSE, we can't return FP values,
1966     // or SSE or MMX vectors.
1967     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1968          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1969           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1970       report_fatal_error("SSE register return with SSE disabled");
1971     }
1972     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1973     // llvm-gcc has never done it right and no one has noticed, so this
1974     // should be OK for now.
1975     if (ValVT == MVT::f64 &&
1976         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1977       report_fatal_error("SSE2 register return with SSE2 disabled");
1978
1979     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1980     // the RET instruction and handled by the FP Stackifier.
1981     if (VA.getLocReg() == X86::FP0 ||
1982         VA.getLocReg() == X86::FP1) {
1983       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1984       // change the value to the FP stack register class.
1985       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1986         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1987       RetOps.push_back(ValToCopy);
1988       // Don't emit a copytoreg.
1989       continue;
1990     }
1991
1992     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1993     // which is returned in RAX / RDX.
1994     if (Subtarget->is64Bit()) {
1995       if (ValVT == MVT::x86mmx) {
1996         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1997           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1998           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1999                                   ValToCopy);
2000           // If we don't have SSE2 available, convert to v4f32 so the generated
2001           // register is legal.
2002           if (!Subtarget->hasSSE2())
2003             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2004         }
2005       }
2006     }
2007
2008     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2009     Flag = Chain.getValue(1);
2010     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2011   }
2012
2013   // All x86 ABIs require that for returning structs by value we copy
2014   // the sret argument into %rax/%eax (depending on ABI) for the return.
2015   // We saved the argument into a virtual register in the entry block,
2016   // so now we copy the value out and into %rax/%eax.
2017   //
2018   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2019   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2020   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2021   // either case FuncInfo->setSRetReturnReg() will have been called.
2022   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2023     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2024
2025     unsigned RetValReg
2026         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2027           X86::RAX : X86::EAX;
2028     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2029     Flag = Chain.getValue(1);
2030
2031     // RAX/EAX now acts like a return value.
2032     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2033   }
2034
2035   RetOps[0] = Chain;  // Update chain.
2036
2037   // Add the flag if we have it.
2038   if (Flag.getNode())
2039     RetOps.push_back(Flag);
2040
2041   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2042 }
2043
2044 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2045   if (N->getNumValues() != 1)
2046     return false;
2047   if (!N->hasNUsesOfValue(1, 0))
2048     return false;
2049
2050   SDValue TCChain = Chain;
2051   SDNode *Copy = *N->use_begin();
2052   if (Copy->getOpcode() == ISD::CopyToReg) {
2053     // If the copy has a glue operand, we conservatively assume it isn't safe to
2054     // perform a tail call.
2055     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2056       return false;
2057     TCChain = Copy->getOperand(0);
2058   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2059     return false;
2060
2061   bool HasRet = false;
2062   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2063        UI != UE; ++UI) {
2064     if (UI->getOpcode() != X86ISD::RET_FLAG)
2065       return false;
2066     // If we are returning more than one value, we can definitely
2067     // not make a tail call see PR19530
2068     if (UI->getNumOperands() > 4)
2069       return false;
2070     if (UI->getNumOperands() == 4 &&
2071         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2072       return false;
2073     HasRet = true;
2074   }
2075
2076   if (!HasRet)
2077     return false;
2078
2079   Chain = TCChain;
2080   return true;
2081 }
2082
2083 EVT
2084 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2085                                             ISD::NodeType ExtendKind) const {
2086   MVT ReturnMVT;
2087   // TODO: Is this also valid on 32-bit?
2088   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2089     ReturnMVT = MVT::i8;
2090   else
2091     ReturnMVT = MVT::i32;
2092
2093   EVT MinVT = getRegisterType(Context, ReturnMVT);
2094   return VT.bitsLT(MinVT) ? MinVT : VT;
2095 }
2096
2097 /// Lower the result values of a call into the
2098 /// appropriate copies out of appropriate physical registers.
2099 ///
2100 SDValue
2101 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2102                                    CallingConv::ID CallConv, bool isVarArg,
2103                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2104                                    SDLoc dl, SelectionDAG &DAG,
2105                                    SmallVectorImpl<SDValue> &InVals) const {
2106
2107   // Assign locations to each value returned by this call.
2108   SmallVector<CCValAssign, 16> RVLocs;
2109   bool Is64Bit = Subtarget->is64Bit();
2110   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2111                  *DAG.getContext());
2112   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2113
2114   // Copy all of the result registers out of their specified physreg.
2115   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2116     CCValAssign &VA = RVLocs[i];
2117     EVT CopyVT = VA.getLocVT();
2118
2119     // If this is x86-64, and we disabled SSE, we can't return FP values
2120     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2121         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2122       report_fatal_error("SSE register return with SSE disabled");
2123     }
2124
2125     // If we prefer to use the value in xmm registers, copy it out as f80 and
2126     // use a truncate to move it from fp stack reg to xmm reg.
2127     bool RoundAfterCopy = false;
2128     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2129         isScalarFPTypeInSSEReg(VA.getValVT())) {
2130       CopyVT = MVT::f80;
2131       RoundAfterCopy = (CopyVT != VA.getLocVT());
2132     }
2133
2134     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2135                                CopyVT, InFlag).getValue(1);
2136     SDValue Val = Chain.getValue(0);
2137
2138     if (RoundAfterCopy)
2139       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2140                         // This truncation won't change the value.
2141                         DAG.getIntPtrConstant(1, dl));
2142
2143     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2144       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2145
2146     InFlag = Chain.getValue(2);
2147     InVals.push_back(Val);
2148   }
2149
2150   return Chain;
2151 }
2152
2153 //===----------------------------------------------------------------------===//
2154 //                C & StdCall & Fast Calling Convention implementation
2155 //===----------------------------------------------------------------------===//
2156 //  StdCall calling convention seems to be standard for many Windows' API
2157 //  routines and around. It differs from C calling convention just a little:
2158 //  callee should clean up the stack, not caller. Symbols should be also
2159 //  decorated in some fancy way :) It doesn't support any vector arguments.
2160 //  For info on fast calling convention see Fast Calling Convention (tail call)
2161 //  implementation LowerX86_32FastCCCallTo.
2162
2163 /// CallIsStructReturn - Determines whether a call uses struct return
2164 /// semantics.
2165 enum StructReturnType {
2166   NotStructReturn,
2167   RegStructReturn,
2168   StackStructReturn
2169 };
2170 static StructReturnType
2171 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2172   if (Outs.empty())
2173     return NotStructReturn;
2174
2175   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2176   if (!Flags.isSRet())
2177     return NotStructReturn;
2178   if (Flags.isInReg())
2179     return RegStructReturn;
2180   return StackStructReturn;
2181 }
2182
2183 /// Determines whether a function uses struct return semantics.
2184 static StructReturnType
2185 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2186   if (Ins.empty())
2187     return NotStructReturn;
2188
2189   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2190   if (!Flags.isSRet())
2191     return NotStructReturn;
2192   if (Flags.isInReg())
2193     return RegStructReturn;
2194   return StackStructReturn;
2195 }
2196
2197 /// Make a copy of an aggregate at address specified by "Src" to address
2198 /// "Dst" with size and alignment information specified by the specific
2199 /// parameter attribute. The copy will be passed as a byval function parameter.
2200 static SDValue
2201 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2202                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2203                           SDLoc dl) {
2204   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2205
2206   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2207                        /*isVolatile*/false, /*AlwaysInline=*/true,
2208                        /*isTailCall*/false,
2209                        MachinePointerInfo(), MachinePointerInfo());
2210 }
2211
2212 /// Return true if the calling convention is one that
2213 /// supports tail call optimization.
2214 static bool IsTailCallConvention(CallingConv::ID CC) {
2215   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2216           CC == CallingConv::HiPE);
2217 }
2218
2219 /// \brief Return true if the calling convention is a C calling convention.
2220 static bool IsCCallConvention(CallingConv::ID CC) {
2221   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2222           CC == CallingConv::X86_64_SysV);
2223 }
2224
2225 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2226   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2227     return false;
2228
2229   CallSite CS(CI);
2230   CallingConv::ID CalleeCC = CS.getCallingConv();
2231   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2232     return false;
2233
2234   return true;
2235 }
2236
2237 /// Return true if the function is being made into
2238 /// a tailcall target by changing its ABI.
2239 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2240                                    bool GuaranteedTailCallOpt) {
2241   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2242 }
2243
2244 SDValue
2245 X86TargetLowering::LowerMemArgument(SDValue Chain,
2246                                     CallingConv::ID CallConv,
2247                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2248                                     SDLoc dl, SelectionDAG &DAG,
2249                                     const CCValAssign &VA,
2250                                     MachineFrameInfo *MFI,
2251                                     unsigned i) const {
2252   // Create the nodes corresponding to a load from this parameter slot.
2253   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2254   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2255       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2256   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2257   EVT ValVT;
2258
2259   // If value is passed by pointer we have address passed instead of the value
2260   // itself.
2261   bool ExtendedInMem = VA.isExtInLoc() &&
2262     VA.getValVT().getScalarType() == MVT::i1;
2263
2264   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2265     ValVT = VA.getLocVT();
2266   else
2267     ValVT = VA.getValVT();
2268
2269   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2270   // changed with more analysis.
2271   // In case of tail call optimization mark all arguments mutable. Since they
2272   // could be overwritten by lowering of arguments in case of a tail call.
2273   if (Flags.isByVal()) {
2274     unsigned Bytes = Flags.getByValSize();
2275     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2276     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2277     return DAG.getFrameIndex(FI, getPointerTy());
2278   } else {
2279     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2280                                     VA.getLocMemOffset(), isImmutable);
2281     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2282     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2283                                MachinePointerInfo::getFixedStack(FI),
2284                                false, false, false, 0);
2285     return ExtendedInMem ?
2286       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2287   }
2288 }
2289
2290 // FIXME: Get this from tablegen.
2291 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2292                                                 const X86Subtarget *Subtarget) {
2293   assert(Subtarget->is64Bit());
2294
2295   if (Subtarget->isCallingConvWin64(CallConv)) {
2296     static const MCPhysReg GPR64ArgRegsWin64[] = {
2297       X86::RCX, X86::RDX, X86::R8,  X86::R9
2298     };
2299     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2300   }
2301
2302   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2303     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2304   };
2305   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2306 }
2307
2308 // FIXME: Get this from tablegen.
2309 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2310                                                 CallingConv::ID CallConv,
2311                                                 const X86Subtarget *Subtarget) {
2312   assert(Subtarget->is64Bit());
2313   if (Subtarget->isCallingConvWin64(CallConv)) {
2314     // The XMM registers which might contain var arg parameters are shadowed
2315     // in their paired GPR.  So we only need to save the GPR to their home
2316     // slots.
2317     // TODO: __vectorcall will change this.
2318     return None;
2319   }
2320
2321   const Function *Fn = MF.getFunction();
2322   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2323   bool isSoftFloat = Subtarget->useSoftFloat();
2324   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2325          "SSE register cannot be used when SSE is disabled!");
2326   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2327     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2328     // registers.
2329     return None;
2330
2331   static const MCPhysReg XMMArgRegs64Bit[] = {
2332     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2333     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2334   };
2335   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2336 }
2337
2338 SDValue
2339 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2340                                         CallingConv::ID CallConv,
2341                                         bool isVarArg,
2342                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2343                                         SDLoc dl,
2344                                         SelectionDAG &DAG,
2345                                         SmallVectorImpl<SDValue> &InVals)
2346                                           const {
2347   MachineFunction &MF = DAG.getMachineFunction();
2348   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2349   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2350
2351   const Function* Fn = MF.getFunction();
2352   if (Fn->hasExternalLinkage() &&
2353       Subtarget->isTargetCygMing() &&
2354       Fn->getName() == "main")
2355     FuncInfo->setForceFramePointer(true);
2356
2357   MachineFrameInfo *MFI = MF.getFrameInfo();
2358   bool Is64Bit = Subtarget->is64Bit();
2359   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2360
2361   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2362          "Var args not supported with calling convention fastcc, ghc or hipe");
2363
2364   // Assign locations to all of the incoming arguments.
2365   SmallVector<CCValAssign, 16> ArgLocs;
2366   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2367
2368   // Allocate shadow area for Win64
2369   if (IsWin64)
2370     CCInfo.AllocateStack(32, 8);
2371
2372   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2373
2374   unsigned LastVal = ~0U;
2375   SDValue ArgValue;
2376   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2377     CCValAssign &VA = ArgLocs[i];
2378     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2379     // places.
2380     assert(VA.getValNo() != LastVal &&
2381            "Don't support value assigned to multiple locs yet");
2382     (void)LastVal;
2383     LastVal = VA.getValNo();
2384
2385     if (VA.isRegLoc()) {
2386       EVT RegVT = VA.getLocVT();
2387       const TargetRegisterClass *RC;
2388       if (RegVT == MVT::i32)
2389         RC = &X86::GR32RegClass;
2390       else if (Is64Bit && RegVT == MVT::i64)
2391         RC = &X86::GR64RegClass;
2392       else if (RegVT == MVT::f32)
2393         RC = &X86::FR32RegClass;
2394       else if (RegVT == MVT::f64)
2395         RC = &X86::FR64RegClass;
2396       else if (RegVT.is512BitVector())
2397         RC = &X86::VR512RegClass;
2398       else if (RegVT.is256BitVector())
2399         RC = &X86::VR256RegClass;
2400       else if (RegVT.is128BitVector())
2401         RC = &X86::VR128RegClass;
2402       else if (RegVT == MVT::x86mmx)
2403         RC = &X86::VR64RegClass;
2404       else if (RegVT == MVT::i1)
2405         RC = &X86::VK1RegClass;
2406       else if (RegVT == MVT::v8i1)
2407         RC = &X86::VK8RegClass;
2408       else if (RegVT == MVT::v16i1)
2409         RC = &X86::VK16RegClass;
2410       else if (RegVT == MVT::v32i1)
2411         RC = &X86::VK32RegClass;
2412       else if (RegVT == MVT::v64i1)
2413         RC = &X86::VK64RegClass;
2414       else
2415         llvm_unreachable("Unknown argument type!");
2416
2417       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2418       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2419
2420       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2421       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2422       // right size.
2423       if (VA.getLocInfo() == CCValAssign::SExt)
2424         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2425                                DAG.getValueType(VA.getValVT()));
2426       else if (VA.getLocInfo() == CCValAssign::ZExt)
2427         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2428                                DAG.getValueType(VA.getValVT()));
2429       else if (VA.getLocInfo() == CCValAssign::BCvt)
2430         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2431
2432       if (VA.isExtInLoc()) {
2433         // Handle MMX values passed in XMM regs.
2434         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2435           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2436         else
2437           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2438       }
2439     } else {
2440       assert(VA.isMemLoc());
2441       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2442     }
2443
2444     // If value is passed via pointer - do a load.
2445     if (VA.getLocInfo() == CCValAssign::Indirect)
2446       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2447                              MachinePointerInfo(), false, false, false, 0);
2448
2449     InVals.push_back(ArgValue);
2450   }
2451
2452   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2453     // All x86 ABIs require that for returning structs by value we copy the
2454     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2455     // the argument into a virtual register so that we can access it from the
2456     // return points.
2457     if (Ins[i].Flags.isSRet()) {
2458       unsigned Reg = FuncInfo->getSRetReturnReg();
2459       if (!Reg) {
2460         MVT PtrTy = getPointerTy();
2461         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2462         FuncInfo->setSRetReturnReg(Reg);
2463       }
2464       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2465       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2466       break;
2467     }
2468   }
2469
2470   unsigned StackSize = CCInfo.getNextStackOffset();
2471   // Align stack specially for tail calls.
2472   if (FuncIsMadeTailCallSafe(CallConv,
2473                              MF.getTarget().Options.GuaranteedTailCallOpt))
2474     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2475
2476   // If the function takes variable number of arguments, make a frame index for
2477   // the start of the first vararg value... for expansion of llvm.va_start. We
2478   // can skip this if there are no va_start calls.
2479   if (MFI->hasVAStart() &&
2480       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2481                    CallConv != CallingConv::X86_ThisCall))) {
2482     FuncInfo->setVarArgsFrameIndex(
2483         MFI->CreateFixedObject(1, StackSize, true));
2484   }
2485
2486   MachineModuleInfo &MMI = MF.getMMI();
2487   const Function *WinEHParent = nullptr;
2488   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2489     WinEHParent = MMI.getWinEHParent(Fn);
2490   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2491   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2492
2493   // Figure out if XMM registers are in use.
2494   assert(!(Subtarget->useSoftFloat() &&
2495            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2496          "SSE register cannot be used when SSE is disabled!");
2497
2498   // 64-bit calling conventions support varargs and register parameters, so we
2499   // have to do extra work to spill them in the prologue.
2500   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2501     // Find the first unallocated argument registers.
2502     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2503     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2504     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2505     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2506     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2507            "SSE register cannot be used when SSE is disabled!");
2508
2509     // Gather all the live in physical registers.
2510     SmallVector<SDValue, 6> LiveGPRs;
2511     SmallVector<SDValue, 8> LiveXMMRegs;
2512     SDValue ALVal;
2513     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2514       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2515       LiveGPRs.push_back(
2516           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2517     }
2518     if (!ArgXMMs.empty()) {
2519       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2520       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2521       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2522         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2523         LiveXMMRegs.push_back(
2524             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2525       }
2526     }
2527
2528     if (IsWin64) {
2529       // Get to the caller-allocated home save location.  Add 8 to account
2530       // for the return address.
2531       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2532       FuncInfo->setRegSaveFrameIndex(
2533           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2534       // Fixup to set vararg frame on shadow area (4 x i64).
2535       if (NumIntRegs < 4)
2536         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2537     } else {
2538       // For X86-64, if there are vararg parameters that are passed via
2539       // registers, then we must store them to their spots on the stack so
2540       // they may be loaded by deferencing the result of va_next.
2541       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2542       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2543       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2544           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2545     }
2546
2547     // Store the integer parameter registers.
2548     SmallVector<SDValue, 8> MemOps;
2549     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2550                                       getPointerTy());
2551     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2552     for (SDValue Val : LiveGPRs) {
2553       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2554                                 DAG.getIntPtrConstant(Offset, dl));
2555       SDValue Store =
2556         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2557                      MachinePointerInfo::getFixedStack(
2558                        FuncInfo->getRegSaveFrameIndex(), Offset),
2559                      false, false, 0);
2560       MemOps.push_back(Store);
2561       Offset += 8;
2562     }
2563
2564     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2565       // Now store the XMM (fp + vector) parameter registers.
2566       SmallVector<SDValue, 12> SaveXMMOps;
2567       SaveXMMOps.push_back(Chain);
2568       SaveXMMOps.push_back(ALVal);
2569       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2570                              FuncInfo->getRegSaveFrameIndex(), dl));
2571       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2572                              FuncInfo->getVarArgsFPOffset(), dl));
2573       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2574                         LiveXMMRegs.end());
2575       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2576                                    MVT::Other, SaveXMMOps));
2577     }
2578
2579     if (!MemOps.empty())
2580       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2581   } else if (IsWinEHOutlined) {
2582     // Get to the caller-allocated home save location.  Add 8 to account
2583     // for the return address.
2584     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2585     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2586         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2587
2588     MMI.getWinEHFuncInfo(Fn)
2589         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2590         FuncInfo->getRegSaveFrameIndex();
2591
2592     // Store the second integer parameter (rdx) into rsp+16 relative to the
2593     // stack pointer at the entry of the function.
2594     SDValue RSFIN =
2595         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2596     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2597     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2598     Chain = DAG.getStore(
2599         Val.getValue(1), dl, Val, RSFIN,
2600         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2601         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2602   }
2603
2604   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2605     // Find the largest legal vector type.
2606     MVT VecVT = MVT::Other;
2607     // FIXME: Only some x86_32 calling conventions support AVX512.
2608     if (Subtarget->hasAVX512() &&
2609         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2610                      CallConv == CallingConv::Intel_OCL_BI)))
2611       VecVT = MVT::v16f32;
2612     else if (Subtarget->hasAVX())
2613       VecVT = MVT::v8f32;
2614     else if (Subtarget->hasSSE2())
2615       VecVT = MVT::v4f32;
2616
2617     // We forward some GPRs and some vector types.
2618     SmallVector<MVT, 2> RegParmTypes;
2619     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2620     RegParmTypes.push_back(IntVT);
2621     if (VecVT != MVT::Other)
2622       RegParmTypes.push_back(VecVT);
2623
2624     // Compute the set of forwarded registers. The rest are scratch.
2625     SmallVectorImpl<ForwardedRegister> &Forwards =
2626         FuncInfo->getForwardedMustTailRegParms();
2627     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2628
2629     // Conservatively forward AL on x86_64, since it might be used for varargs.
2630     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2631       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2632       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2633     }
2634
2635     // Copy all forwards from physical to virtual registers.
2636     for (ForwardedRegister &F : Forwards) {
2637       // FIXME: Can we use a less constrained schedule?
2638       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2639       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2640       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2641     }
2642   }
2643
2644   // Some CCs need callee pop.
2645   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2646                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2647     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2648   } else {
2649     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2650     // If this is an sret function, the return should pop the hidden pointer.
2651     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2652         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2653         argsAreStructReturn(Ins) == StackStructReturn)
2654       FuncInfo->setBytesToPopOnReturn(4);
2655   }
2656
2657   if (!Is64Bit) {
2658     // RegSaveFrameIndex is X86-64 only.
2659     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2660     if (CallConv == CallingConv::X86_FastCall ||
2661         CallConv == CallingConv::X86_ThisCall)
2662       // fastcc functions can't have varargs.
2663       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2664   }
2665
2666   FuncInfo->setArgumentStackSize(StackSize);
2667
2668   if (IsWinEHParent) {
2669     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2670     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2671     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2672     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2673     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2674                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2675                          /*isVolatile=*/true,
2676                          /*isNonTemporal=*/false, /*Alignment=*/0);
2677   }
2678
2679   return Chain;
2680 }
2681
2682 SDValue
2683 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2684                                     SDValue StackPtr, SDValue Arg,
2685                                     SDLoc dl, SelectionDAG &DAG,
2686                                     const CCValAssign &VA,
2687                                     ISD::ArgFlagsTy Flags) const {
2688   unsigned LocMemOffset = VA.getLocMemOffset();
2689   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2690   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2691   if (Flags.isByVal())
2692     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2693
2694   return DAG.getStore(Chain, dl, Arg, PtrOff,
2695                       MachinePointerInfo::getStack(LocMemOffset),
2696                       false, false, 0);
2697 }
2698
2699 /// Emit a load of return address if tail call
2700 /// optimization is performed and it is required.
2701 SDValue
2702 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2703                                            SDValue &OutRetAddr, SDValue Chain,
2704                                            bool IsTailCall, bool Is64Bit,
2705                                            int FPDiff, SDLoc dl) const {
2706   // Adjust the Return address stack slot.
2707   EVT VT = getPointerTy();
2708   OutRetAddr = getReturnAddressFrameIndex(DAG);
2709
2710   // Load the "old" Return address.
2711   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2712                            false, false, false, 0);
2713   return SDValue(OutRetAddr.getNode(), 1);
2714 }
2715
2716 /// Emit a store of the return address if tail call
2717 /// optimization is performed and it is required (FPDiff!=0).
2718 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2719                                         SDValue Chain, SDValue RetAddrFrIdx,
2720                                         EVT PtrVT, unsigned SlotSize,
2721                                         int FPDiff, SDLoc dl) {
2722   // Store the return address to the appropriate stack slot.
2723   if (!FPDiff) return Chain;
2724   // Calculate the new stack slot for the return address.
2725   int NewReturnAddrFI =
2726     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2727                                          false);
2728   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2729   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2730                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2731                        false, false, 0);
2732   return Chain;
2733 }
2734
2735 SDValue
2736 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2737                              SmallVectorImpl<SDValue> &InVals) const {
2738   SelectionDAG &DAG                     = CLI.DAG;
2739   SDLoc &dl                             = CLI.DL;
2740   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2741   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2742   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2743   SDValue Chain                         = CLI.Chain;
2744   SDValue Callee                        = CLI.Callee;
2745   CallingConv::ID CallConv              = CLI.CallConv;
2746   bool &isTailCall                      = CLI.IsTailCall;
2747   bool isVarArg                         = CLI.IsVarArg;
2748
2749   MachineFunction &MF = DAG.getMachineFunction();
2750   bool Is64Bit        = Subtarget->is64Bit();
2751   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2752   StructReturnType SR = callIsStructReturn(Outs);
2753   bool IsSibcall      = false;
2754   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2755
2756   if (MF.getTarget().Options.DisableTailCalls)
2757     isTailCall = false;
2758
2759   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2760   if (IsMustTail) {
2761     // Force this to be a tail call.  The verifier rules are enough to ensure
2762     // that we can lower this successfully without moving the return address
2763     // around.
2764     isTailCall = true;
2765   } else if (isTailCall) {
2766     // Check if it's really possible to do a tail call.
2767     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2768                     isVarArg, SR != NotStructReturn,
2769                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2770                     Outs, OutVals, Ins, DAG);
2771
2772     // Sibcalls are automatically detected tailcalls which do not require
2773     // ABI changes.
2774     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2775       IsSibcall = true;
2776
2777     if (isTailCall)
2778       ++NumTailCalls;
2779   }
2780
2781   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2782          "Var args not supported with calling convention fastcc, ghc or hipe");
2783
2784   // Analyze operands of the call, assigning locations to each operand.
2785   SmallVector<CCValAssign, 16> ArgLocs;
2786   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2787
2788   // Allocate shadow area for Win64
2789   if (IsWin64)
2790     CCInfo.AllocateStack(32, 8);
2791
2792   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2793
2794   // Get a count of how many bytes are to be pushed on the stack.
2795   unsigned NumBytes = CCInfo.getNextStackOffset();
2796   if (IsSibcall)
2797     // This is a sibcall. The memory operands are available in caller's
2798     // own caller's stack.
2799     NumBytes = 0;
2800   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2801            IsTailCallConvention(CallConv))
2802     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2803
2804   int FPDiff = 0;
2805   if (isTailCall && !IsSibcall && !IsMustTail) {
2806     // Lower arguments at fp - stackoffset + fpdiff.
2807     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2808
2809     FPDiff = NumBytesCallerPushed - NumBytes;
2810
2811     // Set the delta of movement of the returnaddr stackslot.
2812     // But only set if delta is greater than previous delta.
2813     if (FPDiff < X86Info->getTCReturnAddrDelta())
2814       X86Info->setTCReturnAddrDelta(FPDiff);
2815   }
2816
2817   unsigned NumBytesToPush = NumBytes;
2818   unsigned NumBytesToPop = NumBytes;
2819
2820   // If we have an inalloca argument, all stack space has already been allocated
2821   // for us and be right at the top of the stack.  We don't support multiple
2822   // arguments passed in memory when using inalloca.
2823   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2824     NumBytesToPush = 0;
2825     if (!ArgLocs.back().isMemLoc())
2826       report_fatal_error("cannot use inalloca attribute on a register "
2827                          "parameter");
2828     if (ArgLocs.back().getLocMemOffset() != 0)
2829       report_fatal_error("any parameter with the inalloca attribute must be "
2830                          "the only memory argument");
2831   }
2832
2833   if (!IsSibcall)
2834     Chain = DAG.getCALLSEQ_START(
2835         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2836
2837   SDValue RetAddrFrIdx;
2838   // Load return address for tail calls.
2839   if (isTailCall && FPDiff)
2840     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2841                                     Is64Bit, FPDiff, dl);
2842
2843   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2844   SmallVector<SDValue, 8> MemOpChains;
2845   SDValue StackPtr;
2846
2847   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2848   // of tail call optimization arguments are handle later.
2849   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2850   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2851     // Skip inalloca arguments, they have already been written.
2852     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2853     if (Flags.isInAlloca())
2854       continue;
2855
2856     CCValAssign &VA = ArgLocs[i];
2857     EVT RegVT = VA.getLocVT();
2858     SDValue Arg = OutVals[i];
2859     bool isByVal = Flags.isByVal();
2860
2861     // Promote the value if needed.
2862     switch (VA.getLocInfo()) {
2863     default: llvm_unreachable("Unknown loc info!");
2864     case CCValAssign::Full: break;
2865     case CCValAssign::SExt:
2866       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2867       break;
2868     case CCValAssign::ZExt:
2869       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2870       break;
2871     case CCValAssign::AExt:
2872       if (Arg.getValueType().isVector() &&
2873           Arg.getValueType().getScalarType() == MVT::i1)
2874         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2875       else if (RegVT.is128BitVector()) {
2876         // Special case: passing MMX values in XMM registers.
2877         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2878         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2879         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2880       } else
2881         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2882       break;
2883     case CCValAssign::BCvt:
2884       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2885       break;
2886     case CCValAssign::Indirect: {
2887       // Store the argument.
2888       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2889       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2890       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2891                            MachinePointerInfo::getFixedStack(FI),
2892                            false, false, 0);
2893       Arg = SpillSlot;
2894       break;
2895     }
2896     }
2897
2898     if (VA.isRegLoc()) {
2899       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2900       if (isVarArg && IsWin64) {
2901         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2902         // shadow reg if callee is a varargs function.
2903         unsigned ShadowReg = 0;
2904         switch (VA.getLocReg()) {
2905         case X86::XMM0: ShadowReg = X86::RCX; break;
2906         case X86::XMM1: ShadowReg = X86::RDX; break;
2907         case X86::XMM2: ShadowReg = X86::R8; break;
2908         case X86::XMM3: ShadowReg = X86::R9; break;
2909         }
2910         if (ShadowReg)
2911           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2912       }
2913     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2914       assert(VA.isMemLoc());
2915       if (!StackPtr.getNode())
2916         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2917                                       getPointerTy());
2918       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2919                                              dl, DAG, VA, Flags));
2920     }
2921   }
2922
2923   if (!MemOpChains.empty())
2924     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2925
2926   if (Subtarget->isPICStyleGOT()) {
2927     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2928     // GOT pointer.
2929     if (!isTailCall) {
2930       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2931                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2932     } else {
2933       // If we are tail calling and generating PIC/GOT style code load the
2934       // address of the callee into ECX. The value in ecx is used as target of
2935       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2936       // for tail calls on PIC/GOT architectures. Normally we would just put the
2937       // address of GOT into ebx and then call target@PLT. But for tail calls
2938       // ebx would be restored (since ebx is callee saved) before jumping to the
2939       // target@PLT.
2940
2941       // Note: The actual moving to ECX is done further down.
2942       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2943       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2944           !G->getGlobal()->hasProtectedVisibility())
2945         Callee = LowerGlobalAddress(Callee, DAG);
2946       else if (isa<ExternalSymbolSDNode>(Callee))
2947         Callee = LowerExternalSymbol(Callee, DAG);
2948     }
2949   }
2950
2951   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2952     // From AMD64 ABI document:
2953     // For calls that may call functions that use varargs or stdargs
2954     // (prototype-less calls or calls to functions containing ellipsis (...) in
2955     // the declaration) %al is used as hidden argument to specify the number
2956     // of SSE registers used. The contents of %al do not need to match exactly
2957     // the number of registers, but must be an ubound on the number of SSE
2958     // registers used and is in the range 0 - 8 inclusive.
2959
2960     // Count the number of XMM registers allocated.
2961     static const MCPhysReg XMMArgRegs[] = {
2962       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2963       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2964     };
2965     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2966     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2967            && "SSE registers cannot be used when SSE is disabled");
2968
2969     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2970                                         DAG.getConstant(NumXMMRegs, dl,
2971                                                         MVT::i8)));
2972   }
2973
2974   if (isVarArg && IsMustTail) {
2975     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2976     for (const auto &F : Forwards) {
2977       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2978       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2979     }
2980   }
2981
2982   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2983   // don't need this because the eligibility check rejects calls that require
2984   // shuffling arguments passed in memory.
2985   if (!IsSibcall && isTailCall) {
2986     // Force all the incoming stack arguments to be loaded from the stack
2987     // before any new outgoing arguments are stored to the stack, because the
2988     // outgoing stack slots may alias the incoming argument stack slots, and
2989     // the alias isn't otherwise explicit. This is slightly more conservative
2990     // than necessary, because it means that each store effectively depends
2991     // on every argument instead of just those arguments it would clobber.
2992     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2993
2994     SmallVector<SDValue, 8> MemOpChains2;
2995     SDValue FIN;
2996     int FI = 0;
2997     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2998       CCValAssign &VA = ArgLocs[i];
2999       if (VA.isRegLoc())
3000         continue;
3001       assert(VA.isMemLoc());
3002       SDValue Arg = OutVals[i];
3003       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3004       // Skip inalloca arguments.  They don't require any work.
3005       if (Flags.isInAlloca())
3006         continue;
3007       // Create frame index.
3008       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3009       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3010       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3011       FIN = DAG.getFrameIndex(FI, getPointerTy());
3012
3013       if (Flags.isByVal()) {
3014         // Copy relative to framepointer.
3015         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3016         if (!StackPtr.getNode())
3017           StackPtr = DAG.getCopyFromReg(Chain, dl,
3018                                         RegInfo->getStackRegister(),
3019                                         getPointerTy());
3020         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3021
3022         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3023                                                          ArgChain,
3024                                                          Flags, DAG, dl));
3025       } else {
3026         // Store relative to framepointer.
3027         MemOpChains2.push_back(
3028           DAG.getStore(ArgChain, dl, Arg, FIN,
3029                        MachinePointerInfo::getFixedStack(FI),
3030                        false, false, 0));
3031       }
3032     }
3033
3034     if (!MemOpChains2.empty())
3035       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3036
3037     // Store the return address to the appropriate stack slot.
3038     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3039                                      getPointerTy(), RegInfo->getSlotSize(),
3040                                      FPDiff, dl);
3041   }
3042
3043   // Build a sequence of copy-to-reg nodes chained together with token chain
3044   // and flag operands which copy the outgoing args into registers.
3045   SDValue InFlag;
3046   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3047     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3048                              RegsToPass[i].second, InFlag);
3049     InFlag = Chain.getValue(1);
3050   }
3051
3052   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3053     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3054     // In the 64-bit large code model, we have to make all calls
3055     // through a register, since the call instruction's 32-bit
3056     // pc-relative offset may not be large enough to hold the whole
3057     // address.
3058   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3059     // If the callee is a GlobalAddress node (quite common, every direct call
3060     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3061     // it.
3062     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3063
3064     // We should use extra load for direct calls to dllimported functions in
3065     // non-JIT mode.
3066     const GlobalValue *GV = G->getGlobal();
3067     if (!GV->hasDLLImportStorageClass()) {
3068       unsigned char OpFlags = 0;
3069       bool ExtraLoad = false;
3070       unsigned WrapperKind = ISD::DELETED_NODE;
3071
3072       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3073       // external symbols most go through the PLT in PIC mode.  If the symbol
3074       // has hidden or protected visibility, or if it is static or local, then
3075       // we don't need to use the PLT - we can directly call it.
3076       if (Subtarget->isTargetELF() &&
3077           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3078           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3079         OpFlags = X86II::MO_PLT;
3080       } else if (Subtarget->isPICStyleStubAny() &&
3081                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3082                  (!Subtarget->getTargetTriple().isMacOSX() ||
3083                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3084         // PC-relative references to external symbols should go through $stub,
3085         // unless we're building with the leopard linker or later, which
3086         // automatically synthesizes these stubs.
3087         OpFlags = X86II::MO_DARWIN_STUB;
3088       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3089                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3090         // If the function is marked as non-lazy, generate an indirect call
3091         // which loads from the GOT directly. This avoids runtime overhead
3092         // at the cost of eager binding (and one extra byte of encoding).
3093         OpFlags = X86II::MO_GOTPCREL;
3094         WrapperKind = X86ISD::WrapperRIP;
3095         ExtraLoad = true;
3096       }
3097
3098       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3099                                           G->getOffset(), OpFlags);
3100
3101       // Add a wrapper if needed.
3102       if (WrapperKind != ISD::DELETED_NODE)
3103         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3104       // Add extra indirection if needed.
3105       if (ExtraLoad)
3106         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3107                              MachinePointerInfo::getGOT(),
3108                              false, false, false, 0);
3109     }
3110   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3111     unsigned char OpFlags = 0;
3112
3113     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3114     // external symbols should go through the PLT.
3115     if (Subtarget->isTargetELF() &&
3116         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3117       OpFlags = X86II::MO_PLT;
3118     } else if (Subtarget->isPICStyleStubAny() &&
3119                (!Subtarget->getTargetTriple().isMacOSX() ||
3120                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3121       // PC-relative references to external symbols should go through $stub,
3122       // unless we're building with the leopard linker or later, which
3123       // automatically synthesizes these stubs.
3124       OpFlags = X86II::MO_DARWIN_STUB;
3125     }
3126
3127     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3128                                          OpFlags);
3129   } else if (Subtarget->isTarget64BitILP32() &&
3130              Callee->getValueType(0) == MVT::i32) {
3131     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3132     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3133   }
3134
3135   // Returns a chain & a flag for retval copy to use.
3136   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3137   SmallVector<SDValue, 8> Ops;
3138
3139   if (!IsSibcall && isTailCall) {
3140     Chain = DAG.getCALLSEQ_END(Chain,
3141                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3142                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3143     InFlag = Chain.getValue(1);
3144   }
3145
3146   Ops.push_back(Chain);
3147   Ops.push_back(Callee);
3148
3149   if (isTailCall)
3150     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3151
3152   // Add argument registers to the end of the list so that they are known live
3153   // into the call.
3154   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3155     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3156                                   RegsToPass[i].second.getValueType()));
3157
3158   // Add a register mask operand representing the call-preserved registers.
3159   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3160   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3161   assert(Mask && "Missing call preserved mask for calling convention");
3162   Ops.push_back(DAG.getRegisterMask(Mask));
3163
3164   if (InFlag.getNode())
3165     Ops.push_back(InFlag);
3166
3167   if (isTailCall) {
3168     // We used to do:
3169     //// If this is the first return lowered for this function, add the regs
3170     //// to the liveout set for the function.
3171     // This isn't right, although it's probably harmless on x86; liveouts
3172     // should be computed from returns not tail calls.  Consider a void
3173     // function making a tail call to a function returning int.
3174     MF.getFrameInfo()->setHasTailCall();
3175     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3176   }
3177
3178   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3179   InFlag = Chain.getValue(1);
3180
3181   // Create the CALLSEQ_END node.
3182   unsigned NumBytesForCalleeToPop;
3183   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3184                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3185     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3186   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3187            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3188            SR == StackStructReturn)
3189     // If this is a call to a struct-return function, the callee
3190     // pops the hidden struct pointer, so we have to push it back.
3191     // This is common for Darwin/X86, Linux & Mingw32 targets.
3192     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3193     NumBytesForCalleeToPop = 4;
3194   else
3195     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3196
3197   // Returns a flag for retval copy to use.
3198   if (!IsSibcall) {
3199     Chain = DAG.getCALLSEQ_END(Chain,
3200                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3201                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3202                                                      true),
3203                                InFlag, dl);
3204     InFlag = Chain.getValue(1);
3205   }
3206
3207   // Handle result values, copying them out of physregs into vregs that we
3208   // return.
3209   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3210                          Ins, dl, DAG, InVals);
3211 }
3212
3213 //===----------------------------------------------------------------------===//
3214 //                Fast Calling Convention (tail call) implementation
3215 //===----------------------------------------------------------------------===//
3216
3217 //  Like std call, callee cleans arguments, convention except that ECX is
3218 //  reserved for storing the tail called function address. Only 2 registers are
3219 //  free for argument passing (inreg). Tail call optimization is performed
3220 //  provided:
3221 //                * tailcallopt is enabled
3222 //                * caller/callee are fastcc
3223 //  On X86_64 architecture with GOT-style position independent code only local
3224 //  (within module) calls are supported at the moment.
3225 //  To keep the stack aligned according to platform abi the function
3226 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3227 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3228 //  If a tail called function callee has more arguments than the caller the
3229 //  caller needs to make sure that there is room to move the RETADDR to. This is
3230 //  achieved by reserving an area the size of the argument delta right after the
3231 //  original RETADDR, but before the saved framepointer or the spilled registers
3232 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3233 //  stack layout:
3234 //    arg1
3235 //    arg2
3236 //    RETADDR
3237 //    [ new RETADDR
3238 //      move area ]
3239 //    (possible EBP)
3240 //    ESI
3241 //    EDI
3242 //    local1 ..
3243
3244 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3245 /// for a 16 byte align requirement.
3246 unsigned
3247 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3248                                                SelectionDAG& DAG) const {
3249   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3250   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3251   unsigned StackAlignment = TFI.getStackAlignment();
3252   uint64_t AlignMask = StackAlignment - 1;
3253   int64_t Offset = StackSize;
3254   unsigned SlotSize = RegInfo->getSlotSize();
3255   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3256     // Number smaller than 12 so just add the difference.
3257     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3258   } else {
3259     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3260     Offset = ((~AlignMask) & Offset) + StackAlignment +
3261       (StackAlignment-SlotSize);
3262   }
3263   return Offset;
3264 }
3265
3266 /// MatchingStackOffset - Return true if the given stack call argument is
3267 /// already available in the same position (relatively) of the caller's
3268 /// incoming argument stack.
3269 static
3270 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3271                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3272                          const X86InstrInfo *TII) {
3273   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3274   int FI = INT_MAX;
3275   if (Arg.getOpcode() == ISD::CopyFromReg) {
3276     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3277     if (!TargetRegisterInfo::isVirtualRegister(VR))
3278       return false;
3279     MachineInstr *Def = MRI->getVRegDef(VR);
3280     if (!Def)
3281       return false;
3282     if (!Flags.isByVal()) {
3283       if (!TII->isLoadFromStackSlot(Def, FI))
3284         return false;
3285     } else {
3286       unsigned Opcode = Def->getOpcode();
3287       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3288            Opcode == X86::LEA64_32r) &&
3289           Def->getOperand(1).isFI()) {
3290         FI = Def->getOperand(1).getIndex();
3291         Bytes = Flags.getByValSize();
3292       } else
3293         return false;
3294     }
3295   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3296     if (Flags.isByVal())
3297       // ByVal argument is passed in as a pointer but it's now being
3298       // dereferenced. e.g.
3299       // define @foo(%struct.X* %A) {
3300       //   tail call @bar(%struct.X* byval %A)
3301       // }
3302       return false;
3303     SDValue Ptr = Ld->getBasePtr();
3304     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3305     if (!FINode)
3306       return false;
3307     FI = FINode->getIndex();
3308   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3309     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3310     FI = FINode->getIndex();
3311     Bytes = Flags.getByValSize();
3312   } else
3313     return false;
3314
3315   assert(FI != INT_MAX);
3316   if (!MFI->isFixedObjectIndex(FI))
3317     return false;
3318   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3319 }
3320
3321 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3322 /// for tail call optimization. Targets which want to do tail call
3323 /// optimization should implement this function.
3324 bool
3325 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3326                                                      CallingConv::ID CalleeCC,
3327                                                      bool isVarArg,
3328                                                      bool isCalleeStructRet,
3329                                                      bool isCallerStructRet,
3330                                                      Type *RetTy,
3331                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3332                                     const SmallVectorImpl<SDValue> &OutVals,
3333                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3334                                                      SelectionDAG &DAG) const {
3335   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3336     return false;
3337
3338   // If -tailcallopt is specified, make fastcc functions tail-callable.
3339   const MachineFunction &MF = DAG.getMachineFunction();
3340   const Function *CallerF = MF.getFunction();
3341
3342   // If the function return type is x86_fp80 and the callee return type is not,
3343   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3344   // perform a tailcall optimization here.
3345   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3346     return false;
3347
3348   CallingConv::ID CallerCC = CallerF->getCallingConv();
3349   bool CCMatch = CallerCC == CalleeCC;
3350   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3351   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3352
3353   // Win64 functions have extra shadow space for argument homing. Don't do the
3354   // sibcall if the caller and callee have mismatched expectations for this
3355   // space.
3356   if (IsCalleeWin64 != IsCallerWin64)
3357     return false;
3358
3359   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3360     if (IsTailCallConvention(CalleeCC) && CCMatch)
3361       return true;
3362     return false;
3363   }
3364
3365   // Look for obvious safe cases to perform tail call optimization that do not
3366   // require ABI changes. This is what gcc calls sibcall.
3367
3368   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3369   // emit a special epilogue.
3370   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3371   if (RegInfo->needsStackRealignment(MF))
3372     return false;
3373
3374   // Also avoid sibcall optimization if either caller or callee uses struct
3375   // return semantics.
3376   if (isCalleeStructRet || isCallerStructRet)
3377     return false;
3378
3379   // An stdcall/thiscall caller is expected to clean up its arguments; the
3380   // callee isn't going to do that.
3381   // FIXME: this is more restrictive than needed. We could produce a tailcall
3382   // when the stack adjustment matches. For example, with a thiscall that takes
3383   // only one argument.
3384   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3385                    CallerCC == CallingConv::X86_ThisCall))
3386     return false;
3387
3388   // Do not sibcall optimize vararg calls unless all arguments are passed via
3389   // registers.
3390   if (isVarArg && !Outs.empty()) {
3391
3392     // Optimizing for varargs on Win64 is unlikely to be safe without
3393     // additional testing.
3394     if (IsCalleeWin64 || IsCallerWin64)
3395       return false;
3396
3397     SmallVector<CCValAssign, 16> ArgLocs;
3398     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3399                    *DAG.getContext());
3400
3401     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3402     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3403       if (!ArgLocs[i].isRegLoc())
3404         return false;
3405   }
3406
3407   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3408   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3409   // this into a sibcall.
3410   bool Unused = false;
3411   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3412     if (!Ins[i].Used) {
3413       Unused = true;
3414       break;
3415     }
3416   }
3417   if (Unused) {
3418     SmallVector<CCValAssign, 16> RVLocs;
3419     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3420                    *DAG.getContext());
3421     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3422     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3423       CCValAssign &VA = RVLocs[i];
3424       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3425         return false;
3426     }
3427   }
3428
3429   // If the calling conventions do not match, then we'd better make sure the
3430   // results are returned in the same way as what the caller expects.
3431   if (!CCMatch) {
3432     SmallVector<CCValAssign, 16> RVLocs1;
3433     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3434                     *DAG.getContext());
3435     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3436
3437     SmallVector<CCValAssign, 16> RVLocs2;
3438     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3439                     *DAG.getContext());
3440     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3441
3442     if (RVLocs1.size() != RVLocs2.size())
3443       return false;
3444     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3445       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3446         return false;
3447       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3448         return false;
3449       if (RVLocs1[i].isRegLoc()) {
3450         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3451           return false;
3452       } else {
3453         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3454           return false;
3455       }
3456     }
3457   }
3458
3459   // If the callee takes no arguments then go on to check the results of the
3460   // call.
3461   if (!Outs.empty()) {
3462     // Check if stack adjustment is needed. For now, do not do this if any
3463     // argument is passed on the stack.
3464     SmallVector<CCValAssign, 16> ArgLocs;
3465     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3466                    *DAG.getContext());
3467
3468     // Allocate shadow area for Win64
3469     if (IsCalleeWin64)
3470       CCInfo.AllocateStack(32, 8);
3471
3472     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3473     if (CCInfo.getNextStackOffset()) {
3474       MachineFunction &MF = DAG.getMachineFunction();
3475       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3476         return false;
3477
3478       // Check if the arguments are already laid out in the right way as
3479       // the caller's fixed stack objects.
3480       MachineFrameInfo *MFI = MF.getFrameInfo();
3481       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3482       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3483       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3484         CCValAssign &VA = ArgLocs[i];
3485         SDValue Arg = OutVals[i];
3486         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3487         if (VA.getLocInfo() == CCValAssign::Indirect)
3488           return false;
3489         if (!VA.isRegLoc()) {
3490           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3491                                    MFI, MRI, TII))
3492             return false;
3493         }
3494       }
3495     }
3496
3497     // If the tailcall address may be in a register, then make sure it's
3498     // possible to register allocate for it. In 32-bit, the call address can
3499     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3500     // callee-saved registers are restored. These happen to be the same
3501     // registers used to pass 'inreg' arguments so watch out for those.
3502     if (!Subtarget->is64Bit() &&
3503         ((!isa<GlobalAddressSDNode>(Callee) &&
3504           !isa<ExternalSymbolSDNode>(Callee)) ||
3505          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3506       unsigned NumInRegs = 0;
3507       // In PIC we need an extra register to formulate the address computation
3508       // for the callee.
3509       unsigned MaxInRegs =
3510         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3511
3512       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3513         CCValAssign &VA = ArgLocs[i];
3514         if (!VA.isRegLoc())
3515           continue;
3516         unsigned Reg = VA.getLocReg();
3517         switch (Reg) {
3518         default: break;
3519         case X86::EAX: case X86::EDX: case X86::ECX:
3520           if (++NumInRegs == MaxInRegs)
3521             return false;
3522           break;
3523         }
3524       }
3525     }
3526   }
3527
3528   return true;
3529 }
3530
3531 FastISel *
3532 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3533                                   const TargetLibraryInfo *libInfo) const {
3534   return X86::createFastISel(funcInfo, libInfo);
3535 }
3536
3537 //===----------------------------------------------------------------------===//
3538 //                           Other Lowering Hooks
3539 //===----------------------------------------------------------------------===//
3540
3541 static bool MayFoldLoad(SDValue Op) {
3542   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3543 }
3544
3545 static bool MayFoldIntoStore(SDValue Op) {
3546   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3547 }
3548
3549 static bool isTargetShuffle(unsigned Opcode) {
3550   switch(Opcode) {
3551   default: return false;
3552   case X86ISD::BLENDI:
3553   case X86ISD::PSHUFB:
3554   case X86ISD::PSHUFD:
3555   case X86ISD::PSHUFHW:
3556   case X86ISD::PSHUFLW:
3557   case X86ISD::SHUFP:
3558   case X86ISD::PALIGNR:
3559   case X86ISD::MOVLHPS:
3560   case X86ISD::MOVLHPD:
3561   case X86ISD::MOVHLPS:
3562   case X86ISD::MOVLPS:
3563   case X86ISD::MOVLPD:
3564   case X86ISD::MOVSHDUP:
3565   case X86ISD::MOVSLDUP:
3566   case X86ISD::MOVDDUP:
3567   case X86ISD::MOVSS:
3568   case X86ISD::MOVSD:
3569   case X86ISD::UNPCKL:
3570   case X86ISD::UNPCKH:
3571   case X86ISD::VPERMILPI:
3572   case X86ISD::VPERM2X128:
3573   case X86ISD::VPERMI:
3574     return true;
3575   }
3576 }
3577
3578 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3579                                     SDValue V1, unsigned TargetMask,
3580                                     SelectionDAG &DAG) {
3581   switch(Opc) {
3582   default: llvm_unreachable("Unknown x86 shuffle node");
3583   case X86ISD::PSHUFD:
3584   case X86ISD::PSHUFHW:
3585   case X86ISD::PSHUFLW:
3586   case X86ISD::VPERMILPI:
3587   case X86ISD::VPERMI:
3588     return DAG.getNode(Opc, dl, VT, V1,
3589                        DAG.getConstant(TargetMask, dl, MVT::i8));
3590   }
3591 }
3592
3593 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3594                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3595   switch(Opc) {
3596   default: llvm_unreachable("Unknown x86 shuffle node");
3597   case X86ISD::MOVLHPS:
3598   case X86ISD::MOVLHPD:
3599   case X86ISD::MOVHLPS:
3600   case X86ISD::MOVLPS:
3601   case X86ISD::MOVLPD:
3602   case X86ISD::MOVSS:
3603   case X86ISD::MOVSD:
3604   case X86ISD::UNPCKL:
3605   case X86ISD::UNPCKH:
3606     return DAG.getNode(Opc, dl, VT, V1, V2);
3607   }
3608 }
3609
3610 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3611   MachineFunction &MF = DAG.getMachineFunction();
3612   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3613   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3614   int ReturnAddrIndex = FuncInfo->getRAIndex();
3615
3616   if (ReturnAddrIndex == 0) {
3617     // Set up a frame object for the return address.
3618     unsigned SlotSize = RegInfo->getSlotSize();
3619     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3620                                                            -(int64_t)SlotSize,
3621                                                            false);
3622     FuncInfo->setRAIndex(ReturnAddrIndex);
3623   }
3624
3625   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3626 }
3627
3628 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3629                                        bool hasSymbolicDisplacement) {
3630   // Offset should fit into 32 bit immediate field.
3631   if (!isInt<32>(Offset))
3632     return false;
3633
3634   // If we don't have a symbolic displacement - we don't have any extra
3635   // restrictions.
3636   if (!hasSymbolicDisplacement)
3637     return true;
3638
3639   // FIXME: Some tweaks might be needed for medium code model.
3640   if (M != CodeModel::Small && M != CodeModel::Kernel)
3641     return false;
3642
3643   // For small code model we assume that latest object is 16MB before end of 31
3644   // bits boundary. We may also accept pretty large negative constants knowing
3645   // that all objects are in the positive half of address space.
3646   if (M == CodeModel::Small && Offset < 16*1024*1024)
3647     return true;
3648
3649   // For kernel code model we know that all object resist in the negative half
3650   // of 32bits address space. We may not accept negative offsets, since they may
3651   // be just off and we may accept pretty large positive ones.
3652   if (M == CodeModel::Kernel && Offset >= 0)
3653     return true;
3654
3655   return false;
3656 }
3657
3658 /// isCalleePop - Determines whether the callee is required to pop its
3659 /// own arguments. Callee pop is necessary to support tail calls.
3660 bool X86::isCalleePop(CallingConv::ID CallingConv,
3661                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3662   switch (CallingConv) {
3663   default:
3664     return false;
3665   case CallingConv::X86_StdCall:
3666   case CallingConv::X86_FastCall:
3667   case CallingConv::X86_ThisCall:
3668     return !is64Bit;
3669   case CallingConv::Fast:
3670   case CallingConv::GHC:
3671   case CallingConv::HiPE:
3672     if (IsVarArg)
3673       return false;
3674     return TailCallOpt;
3675   }
3676 }
3677
3678 /// \brief Return true if the condition is an unsigned comparison operation.
3679 static bool isX86CCUnsigned(unsigned X86CC) {
3680   switch (X86CC) {
3681   default: llvm_unreachable("Invalid integer condition!");
3682   case X86::COND_E:     return true;
3683   case X86::COND_G:     return false;
3684   case X86::COND_GE:    return false;
3685   case X86::COND_L:     return false;
3686   case X86::COND_LE:    return false;
3687   case X86::COND_NE:    return true;
3688   case X86::COND_B:     return true;
3689   case X86::COND_A:     return true;
3690   case X86::COND_BE:    return true;
3691   case X86::COND_AE:    return true;
3692   }
3693   llvm_unreachable("covered switch fell through?!");
3694 }
3695
3696 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3697 /// specific condition code, returning the condition code and the LHS/RHS of the
3698 /// comparison to make.
3699 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3700                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3701   if (!isFP) {
3702     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3703       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3704         // X > -1   -> X == 0, jump !sign.
3705         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3706         return X86::COND_NS;
3707       }
3708       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3709         // X < 0   -> X == 0, jump on sign.
3710         return X86::COND_S;
3711       }
3712       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3713         // X < 1   -> X <= 0
3714         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3715         return X86::COND_LE;
3716       }
3717     }
3718
3719     switch (SetCCOpcode) {
3720     default: llvm_unreachable("Invalid integer condition!");
3721     case ISD::SETEQ:  return X86::COND_E;
3722     case ISD::SETGT:  return X86::COND_G;
3723     case ISD::SETGE:  return X86::COND_GE;
3724     case ISD::SETLT:  return X86::COND_L;
3725     case ISD::SETLE:  return X86::COND_LE;
3726     case ISD::SETNE:  return X86::COND_NE;
3727     case ISD::SETULT: return X86::COND_B;
3728     case ISD::SETUGT: return X86::COND_A;
3729     case ISD::SETULE: return X86::COND_BE;
3730     case ISD::SETUGE: return X86::COND_AE;
3731     }
3732   }
3733
3734   // First determine if it is required or is profitable to flip the operands.
3735
3736   // If LHS is a foldable load, but RHS is not, flip the condition.
3737   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3738       !ISD::isNON_EXTLoad(RHS.getNode())) {
3739     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3740     std::swap(LHS, RHS);
3741   }
3742
3743   switch (SetCCOpcode) {
3744   default: break;
3745   case ISD::SETOLT:
3746   case ISD::SETOLE:
3747   case ISD::SETUGT:
3748   case ISD::SETUGE:
3749     std::swap(LHS, RHS);
3750     break;
3751   }
3752
3753   // On a floating point condition, the flags are set as follows:
3754   // ZF  PF  CF   op
3755   //  0 | 0 | 0 | X > Y
3756   //  0 | 0 | 1 | X < Y
3757   //  1 | 0 | 0 | X == Y
3758   //  1 | 1 | 1 | unordered
3759   switch (SetCCOpcode) {
3760   default: llvm_unreachable("Condcode should be pre-legalized away");
3761   case ISD::SETUEQ:
3762   case ISD::SETEQ:   return X86::COND_E;
3763   case ISD::SETOLT:              // flipped
3764   case ISD::SETOGT:
3765   case ISD::SETGT:   return X86::COND_A;
3766   case ISD::SETOLE:              // flipped
3767   case ISD::SETOGE:
3768   case ISD::SETGE:   return X86::COND_AE;
3769   case ISD::SETUGT:              // flipped
3770   case ISD::SETULT:
3771   case ISD::SETLT:   return X86::COND_B;
3772   case ISD::SETUGE:              // flipped
3773   case ISD::SETULE:
3774   case ISD::SETLE:   return X86::COND_BE;
3775   case ISD::SETONE:
3776   case ISD::SETNE:   return X86::COND_NE;
3777   case ISD::SETUO:   return X86::COND_P;
3778   case ISD::SETO:    return X86::COND_NP;
3779   case ISD::SETOEQ:
3780   case ISD::SETUNE:  return X86::COND_INVALID;
3781   }
3782 }
3783
3784 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3785 /// code. Current x86 isa includes the following FP cmov instructions:
3786 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3787 static bool hasFPCMov(unsigned X86CC) {
3788   switch (X86CC) {
3789   default:
3790     return false;
3791   case X86::COND_B:
3792   case X86::COND_BE:
3793   case X86::COND_E:
3794   case X86::COND_P:
3795   case X86::COND_A:
3796   case X86::COND_AE:
3797   case X86::COND_NE:
3798   case X86::COND_NP:
3799     return true;
3800   }
3801 }
3802
3803 /// isFPImmLegal - Returns true if the target can instruction select the
3804 /// specified FP immediate natively. If false, the legalizer will
3805 /// materialize the FP immediate as a load from a constant pool.
3806 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3807   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3808     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3809       return true;
3810   }
3811   return false;
3812 }
3813
3814 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3815                                               ISD::LoadExtType ExtTy,
3816                                               EVT NewVT) const {
3817   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3818   // relocation target a movq or addq instruction: don't let the load shrink.
3819   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3820   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3821     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3822       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3823   return true;
3824 }
3825
3826 /// \brief Returns true if it is beneficial to convert a load of a constant
3827 /// to just the constant itself.
3828 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3829                                                           Type *Ty) const {
3830   assert(Ty->isIntegerTy());
3831
3832   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3833   if (BitSize == 0 || BitSize > 64)
3834     return false;
3835   return true;
3836 }
3837
3838 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3839                                                 unsigned Index) const {
3840   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3841     return false;
3842
3843   return (Index == 0 || Index == ResVT.getVectorNumElements());
3844 }
3845
3846 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3847   // Speculate cttz only if we can directly use TZCNT.
3848   return Subtarget->hasBMI();
3849 }
3850
3851 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3852   // Speculate ctlz only if we can directly use LZCNT.
3853   return Subtarget->hasLZCNT();
3854 }
3855
3856 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3857 /// the specified range (L, H].
3858 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3859   return (Val < 0) || (Val >= Low && Val < Hi);
3860 }
3861
3862 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3863 /// specified value.
3864 static bool isUndefOrEqual(int Val, int CmpVal) {
3865   return (Val < 0 || Val == CmpVal);
3866 }
3867
3868 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3869 /// from position Pos and ending in Pos+Size, falls within the specified
3870 /// sequential range (Low, Low+Size]. or is undef.
3871 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3872                                        unsigned Pos, unsigned Size, int Low) {
3873   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3874     if (!isUndefOrEqual(Mask[i], Low))
3875       return false;
3876   return true;
3877 }
3878
3879 /// isVEXTRACTIndex - Return true if the specified
3880 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3881 /// suitable for instruction that extract 128 or 256 bit vectors
3882 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3883   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3884   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3885     return false;
3886
3887   // The index should be aligned on a vecWidth-bit boundary.
3888   uint64_t Index =
3889     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3890
3891   MVT VT = N->getSimpleValueType(0);
3892   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3893   bool Result = (Index * ElSize) % vecWidth == 0;
3894
3895   return Result;
3896 }
3897
3898 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3899 /// operand specifies a subvector insert that is suitable for input to
3900 /// insertion of 128 or 256-bit subvectors
3901 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3902   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3903   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3904     return false;
3905   // The index should be aligned on a vecWidth-bit boundary.
3906   uint64_t Index =
3907     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3908
3909   MVT VT = N->getSimpleValueType(0);
3910   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3911   bool Result = (Index * ElSize) % vecWidth == 0;
3912
3913   return Result;
3914 }
3915
3916 bool X86::isVINSERT128Index(SDNode *N) {
3917   return isVINSERTIndex(N, 128);
3918 }
3919
3920 bool X86::isVINSERT256Index(SDNode *N) {
3921   return isVINSERTIndex(N, 256);
3922 }
3923
3924 bool X86::isVEXTRACT128Index(SDNode *N) {
3925   return isVEXTRACTIndex(N, 128);
3926 }
3927
3928 bool X86::isVEXTRACT256Index(SDNode *N) {
3929   return isVEXTRACTIndex(N, 256);
3930 }
3931
3932 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3933   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3934   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3935     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3936
3937   uint64_t Index =
3938     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3939
3940   MVT VecVT = N->getOperand(0).getSimpleValueType();
3941   MVT ElVT = VecVT.getVectorElementType();
3942
3943   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3944   return Index / NumElemsPerChunk;
3945 }
3946
3947 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3948   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3949   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3950     llvm_unreachable("Illegal insert subvector for VINSERT");
3951
3952   uint64_t Index =
3953     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3954
3955   MVT VecVT = N->getSimpleValueType(0);
3956   MVT ElVT = VecVT.getVectorElementType();
3957
3958   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3959   return Index / NumElemsPerChunk;
3960 }
3961
3962 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3963 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3964 /// and VINSERTI128 instructions.
3965 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3966   return getExtractVEXTRACTImmediate(N, 128);
3967 }
3968
3969 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3970 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3971 /// and VINSERTI64x4 instructions.
3972 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3973   return getExtractVEXTRACTImmediate(N, 256);
3974 }
3975
3976 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3977 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3978 /// and VINSERTI128 instructions.
3979 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3980   return getInsertVINSERTImmediate(N, 128);
3981 }
3982
3983 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3984 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3985 /// and VINSERTI64x4 instructions.
3986 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3987   return getInsertVINSERTImmediate(N, 256);
3988 }
3989
3990 /// isZero - Returns true if Elt is a constant integer zero
3991 static bool isZero(SDValue V) {
3992   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3993   return C && C->isNullValue();
3994 }
3995
3996 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3997 /// constant +0.0.
3998 bool X86::isZeroNode(SDValue Elt) {
3999   if (isZero(Elt))
4000     return true;
4001   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4002     return CFP->getValueAPF().isPosZero();
4003   return false;
4004 }
4005
4006 /// getZeroVector - Returns a vector of specified type with all zero elements.
4007 ///
4008 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4009                              SelectionDAG &DAG, SDLoc dl) {
4010   assert(VT.isVector() && "Expected a vector type");
4011
4012   // Always build SSE zero vectors as <4 x i32> bitcasted
4013   // to their dest type. This ensures they get CSE'd.
4014   SDValue Vec;
4015   if (VT.is128BitVector()) {  // SSE
4016     if (Subtarget->hasSSE2()) {  // SSE2
4017       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4018       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4019     } else { // SSE1
4020       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4021       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4022     }
4023   } else if (VT.is256BitVector()) { // AVX
4024     if (Subtarget->hasInt256()) { // AVX2
4025       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4026       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4027       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4028     } else {
4029       // 256-bit logic and arithmetic instructions in AVX are all
4030       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4031       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4032       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4033       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4034     }
4035   } else if (VT.is512BitVector()) { // AVX-512
4036       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4037       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4038                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4039       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4040   } else if (VT.getScalarType() == MVT::i1) {
4041
4042     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4043             && "Unexpected vector type");
4044     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4045             && "Unexpected vector type");
4046     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4047     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4048     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4049   } else
4050     llvm_unreachable("Unexpected vector type");
4051
4052   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4053 }
4054
4055 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4056                                 SelectionDAG &DAG, SDLoc dl,
4057                                 unsigned vectorWidth) {
4058   assert((vectorWidth == 128 || vectorWidth == 256) &&
4059          "Unsupported vector width");
4060   EVT VT = Vec.getValueType();
4061   EVT ElVT = VT.getVectorElementType();
4062   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4063   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4064                                   VT.getVectorNumElements()/Factor);
4065
4066   // Extract from UNDEF is UNDEF.
4067   if (Vec.getOpcode() == ISD::UNDEF)
4068     return DAG.getUNDEF(ResultVT);
4069
4070   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4071   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4072
4073   // This is the index of the first element of the vectorWidth-bit chunk
4074   // we want.
4075   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4076                                * ElemsPerChunk);
4077
4078   // If the input is a buildvector just emit a smaller one.
4079   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4080     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4081                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4082                                     ElemsPerChunk));
4083
4084   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4085   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4086 }
4087
4088 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4089 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4090 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4091 /// instructions or a simple subregister reference. Idx is an index in the
4092 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4093 /// lowering EXTRACT_VECTOR_ELT operations easier.
4094 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4095                                    SelectionDAG &DAG, SDLoc dl) {
4096   assert((Vec.getValueType().is256BitVector() ||
4097           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4098   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4099 }
4100
4101 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4102 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4103                                    SelectionDAG &DAG, SDLoc dl) {
4104   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4105   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4106 }
4107
4108 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4109                                unsigned IdxVal, SelectionDAG &DAG,
4110                                SDLoc dl, unsigned vectorWidth) {
4111   assert((vectorWidth == 128 || vectorWidth == 256) &&
4112          "Unsupported vector width");
4113   // Inserting UNDEF is Result
4114   if (Vec.getOpcode() == ISD::UNDEF)
4115     return Result;
4116   EVT VT = Vec.getValueType();
4117   EVT ElVT = VT.getVectorElementType();
4118   EVT ResultVT = Result.getValueType();
4119
4120   // Insert the relevant vectorWidth bits.
4121   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4122
4123   // This is the index of the first element of the vectorWidth-bit chunk
4124   // we want.
4125   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4126                                * ElemsPerChunk);
4127
4128   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4129   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4130 }
4131
4132 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4133 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4134 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4135 /// simple superregister reference.  Idx is an index in the 128 bits
4136 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4137 /// lowering INSERT_VECTOR_ELT operations easier.
4138 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4139                                   SelectionDAG &DAG, SDLoc dl) {
4140   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4141
4142   // For insertion into the zero index (low half) of a 256-bit vector, it is
4143   // more efficient to generate a blend with immediate instead of an insert*128.
4144   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4145   // extend the subvector to the size of the result vector. Make sure that
4146   // we are not recursing on that node by checking for undef here.
4147   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4148       Result.getOpcode() != ISD::UNDEF) {
4149     EVT ResultVT = Result.getValueType();
4150     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4151     SDValue Undef = DAG.getUNDEF(ResultVT);
4152     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4153                                  Vec, ZeroIndex);
4154
4155     // The blend instruction, and therefore its mask, depend on the data type.
4156     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4157     if (ScalarType.isFloatingPoint()) {
4158       // Choose either vblendps (float) or vblendpd (double).
4159       unsigned ScalarSize = ScalarType.getSizeInBits();
4160       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4161       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4162       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4163       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4164     }
4165
4166     const X86Subtarget &Subtarget =
4167     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4168
4169     // AVX2 is needed for 256-bit integer blend support.
4170     // Integers must be cast to 32-bit because there is only vpblendd;
4171     // vpblendw can't be used for this because it has a handicapped mask.
4172
4173     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4174     // is still more efficient than using the wrong domain vinsertf128 that
4175     // will be created by InsertSubVector().
4176     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4177
4178     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4179     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4180     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4181     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4182   }
4183
4184   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4185 }
4186
4187 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4188                                   SelectionDAG &DAG, SDLoc dl) {
4189   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4190   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4191 }
4192
4193 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4194 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4195 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4196 /// large BUILD_VECTORS.
4197 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4198                                    unsigned NumElems, SelectionDAG &DAG,
4199                                    SDLoc dl) {
4200   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4201   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4202 }
4203
4204 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4205                                    unsigned NumElems, SelectionDAG &DAG,
4206                                    SDLoc dl) {
4207   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4208   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4209 }
4210
4211 /// getOnesVector - Returns a vector of specified type with all bits set.
4212 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4213 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4214 /// Then bitcast to their original type, ensuring they get CSE'd.
4215 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4216                              SDLoc dl) {
4217   assert(VT.isVector() && "Expected a vector type");
4218
4219   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4220   SDValue Vec;
4221   if (VT.is256BitVector()) {
4222     if (HasInt256) { // AVX2
4223       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4224       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4225     } else { // AVX
4226       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4227       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4228     }
4229   } else if (VT.is128BitVector()) {
4230     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4231   } else
4232     llvm_unreachable("Unexpected vector type");
4233
4234   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4235 }
4236
4237 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4238 /// operation of specified width.
4239 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4240                        SDValue V2) {
4241   unsigned NumElems = VT.getVectorNumElements();
4242   SmallVector<int, 8> Mask;
4243   Mask.push_back(NumElems);
4244   for (unsigned i = 1; i != NumElems; ++i)
4245     Mask.push_back(i);
4246   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4247 }
4248
4249 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4250 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4251                           SDValue V2) {
4252   unsigned NumElems = VT.getVectorNumElements();
4253   SmallVector<int, 8> Mask;
4254   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4255     Mask.push_back(i);
4256     Mask.push_back(i + NumElems);
4257   }
4258   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4259 }
4260
4261 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4262 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4263                           SDValue V2) {
4264   unsigned NumElems = VT.getVectorNumElements();
4265   SmallVector<int, 8> Mask;
4266   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4267     Mask.push_back(i + Half);
4268     Mask.push_back(i + NumElems + Half);
4269   }
4270   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4271 }
4272
4273 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4274 /// vector of zero or undef vector.  This produces a shuffle where the low
4275 /// element of V2 is swizzled into the zero/undef vector, landing at element
4276 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4277 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4278                                            bool IsZero,
4279                                            const X86Subtarget *Subtarget,
4280                                            SelectionDAG &DAG) {
4281   MVT VT = V2.getSimpleValueType();
4282   SDValue V1 = IsZero
4283     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4284   unsigned NumElems = VT.getVectorNumElements();
4285   SmallVector<int, 16> MaskVec;
4286   for (unsigned i = 0; i != NumElems; ++i)
4287     // If this is the insertion idx, put the low elt of V2 here.
4288     MaskVec.push_back(i == Idx ? NumElems : i);
4289   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4290 }
4291
4292 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4293 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4294 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4295 /// shuffles which use a single input multiple times, and in those cases it will
4296 /// adjust the mask to only have indices within that single input.
4297 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4298                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4299   unsigned NumElems = VT.getVectorNumElements();
4300   SDValue ImmN;
4301
4302   IsUnary = false;
4303   bool IsFakeUnary = false;
4304   switch(N->getOpcode()) {
4305   case X86ISD::BLENDI:
4306     ImmN = N->getOperand(N->getNumOperands()-1);
4307     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4308     break;
4309   case X86ISD::SHUFP:
4310     ImmN = N->getOperand(N->getNumOperands()-1);
4311     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4312     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4313     break;
4314   case X86ISD::UNPCKH:
4315     DecodeUNPCKHMask(VT, Mask);
4316     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4317     break;
4318   case X86ISD::UNPCKL:
4319     DecodeUNPCKLMask(VT, Mask);
4320     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4321     break;
4322   case X86ISD::MOVHLPS:
4323     DecodeMOVHLPSMask(NumElems, Mask);
4324     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4325     break;
4326   case X86ISD::MOVLHPS:
4327     DecodeMOVLHPSMask(NumElems, Mask);
4328     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4329     break;
4330   case X86ISD::PALIGNR:
4331     ImmN = N->getOperand(N->getNumOperands()-1);
4332     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4333     break;
4334   case X86ISD::PSHUFD:
4335   case X86ISD::VPERMILPI:
4336     ImmN = N->getOperand(N->getNumOperands()-1);
4337     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4338     IsUnary = true;
4339     break;
4340   case X86ISD::PSHUFHW:
4341     ImmN = N->getOperand(N->getNumOperands()-1);
4342     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4343     IsUnary = true;
4344     break;
4345   case X86ISD::PSHUFLW:
4346     ImmN = N->getOperand(N->getNumOperands()-1);
4347     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4348     IsUnary = true;
4349     break;
4350   case X86ISD::PSHUFB: {
4351     IsUnary = true;
4352     SDValue MaskNode = N->getOperand(1);
4353     while (MaskNode->getOpcode() == ISD::BITCAST)
4354       MaskNode = MaskNode->getOperand(0);
4355
4356     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4357       // If we have a build-vector, then things are easy.
4358       EVT VT = MaskNode.getValueType();
4359       assert(VT.isVector() &&
4360              "Can't produce a non-vector with a build_vector!");
4361       if (!VT.isInteger())
4362         return false;
4363
4364       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4365
4366       SmallVector<uint64_t, 32> RawMask;
4367       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4368         SDValue Op = MaskNode->getOperand(i);
4369         if (Op->getOpcode() == ISD::UNDEF) {
4370           RawMask.push_back((uint64_t)SM_SentinelUndef);
4371           continue;
4372         }
4373         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4374         if (!CN)
4375           return false;
4376         APInt MaskElement = CN->getAPIntValue();
4377
4378         // We now have to decode the element which could be any integer size and
4379         // extract each byte of it.
4380         for (int j = 0; j < NumBytesPerElement; ++j) {
4381           // Note that this is x86 and so always little endian: the low byte is
4382           // the first byte of the mask.
4383           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4384           MaskElement = MaskElement.lshr(8);
4385         }
4386       }
4387       DecodePSHUFBMask(RawMask, Mask);
4388       break;
4389     }
4390
4391     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4392     if (!MaskLoad)
4393       return false;
4394
4395     SDValue Ptr = MaskLoad->getBasePtr();
4396     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4397         Ptr->getOpcode() == X86ISD::WrapperRIP)
4398       Ptr = Ptr->getOperand(0);
4399
4400     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4401     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4402       return false;
4403
4404     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4405       DecodePSHUFBMask(C, Mask);
4406       if (Mask.empty())
4407         return false;
4408       break;
4409     }
4410
4411     return false;
4412   }
4413   case X86ISD::VPERMI:
4414     ImmN = N->getOperand(N->getNumOperands()-1);
4415     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4416     IsUnary = true;
4417     break;
4418   case X86ISD::MOVSS:
4419   case X86ISD::MOVSD:
4420     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4421     break;
4422   case X86ISD::VPERM2X128:
4423     ImmN = N->getOperand(N->getNumOperands()-1);
4424     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4425     if (Mask.empty()) return false;
4426     break;
4427   case X86ISD::MOVSLDUP:
4428     DecodeMOVSLDUPMask(VT, Mask);
4429     IsUnary = true;
4430     break;
4431   case X86ISD::MOVSHDUP:
4432     DecodeMOVSHDUPMask(VT, Mask);
4433     IsUnary = true;
4434     break;
4435   case X86ISD::MOVDDUP:
4436     DecodeMOVDDUPMask(VT, Mask);
4437     IsUnary = true;
4438     break;
4439   case X86ISD::MOVLHPD:
4440   case X86ISD::MOVLPD:
4441   case X86ISD::MOVLPS:
4442     // Not yet implemented
4443     return false;
4444   default: llvm_unreachable("unknown target shuffle node");
4445   }
4446
4447   // If we have a fake unary shuffle, the shuffle mask is spread across two
4448   // inputs that are actually the same node. Re-map the mask to always point
4449   // into the first input.
4450   if (IsFakeUnary)
4451     for (int &M : Mask)
4452       if (M >= (int)Mask.size())
4453         M -= Mask.size();
4454
4455   return true;
4456 }
4457
4458 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4459 /// element of the result of the vector shuffle.
4460 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4461                                    unsigned Depth) {
4462   if (Depth == 6)
4463     return SDValue();  // Limit search depth.
4464
4465   SDValue V = SDValue(N, 0);
4466   EVT VT = V.getValueType();
4467   unsigned Opcode = V.getOpcode();
4468
4469   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4470   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4471     int Elt = SV->getMaskElt(Index);
4472
4473     if (Elt < 0)
4474       return DAG.getUNDEF(VT.getVectorElementType());
4475
4476     unsigned NumElems = VT.getVectorNumElements();
4477     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4478                                          : SV->getOperand(1);
4479     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4480   }
4481
4482   // Recurse into target specific vector shuffles to find scalars.
4483   if (isTargetShuffle(Opcode)) {
4484     MVT ShufVT = V.getSimpleValueType();
4485     unsigned NumElems = ShufVT.getVectorNumElements();
4486     SmallVector<int, 16> ShuffleMask;
4487     bool IsUnary;
4488
4489     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4490       return SDValue();
4491
4492     int Elt = ShuffleMask[Index];
4493     if (Elt < 0)
4494       return DAG.getUNDEF(ShufVT.getVectorElementType());
4495
4496     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4497                                          : N->getOperand(1);
4498     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4499                                Depth+1);
4500   }
4501
4502   // Actual nodes that may contain scalar elements
4503   if (Opcode == ISD::BITCAST) {
4504     V = V.getOperand(0);
4505     EVT SrcVT = V.getValueType();
4506     unsigned NumElems = VT.getVectorNumElements();
4507
4508     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4509       return SDValue();
4510   }
4511
4512   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4513     return (Index == 0) ? V.getOperand(0)
4514                         : DAG.getUNDEF(VT.getVectorElementType());
4515
4516   if (V.getOpcode() == ISD::BUILD_VECTOR)
4517     return V.getOperand(Index);
4518
4519   return SDValue();
4520 }
4521
4522 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4523 ///
4524 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4525                                        unsigned NumNonZero, unsigned NumZero,
4526                                        SelectionDAG &DAG,
4527                                        const X86Subtarget* Subtarget,
4528                                        const TargetLowering &TLI) {
4529   if (NumNonZero > 8)
4530     return SDValue();
4531
4532   SDLoc dl(Op);
4533   SDValue V;
4534   bool First = true;
4535
4536   // SSE4.1 - use PINSRB to insert each byte directly.
4537   if (Subtarget->hasSSE41()) {
4538     for (unsigned i = 0; i < 16; ++i) {
4539       bool isNonZero = (NonZeros & (1 << i)) != 0;
4540       if (isNonZero) {
4541         if (First) {
4542           if (NumZero)
4543             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4544           else
4545             V = DAG.getUNDEF(MVT::v16i8);
4546           First = false;
4547         }
4548         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4549                         MVT::v16i8, V, Op.getOperand(i),
4550                         DAG.getIntPtrConstant(i, dl));
4551       }
4552     }
4553
4554     return V;
4555   }
4556
4557   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4558   for (unsigned i = 0; i < 16; ++i) {
4559     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4560     if (ThisIsNonZero && First) {
4561       if (NumZero)
4562         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4563       else
4564         V = DAG.getUNDEF(MVT::v8i16);
4565       First = false;
4566     }
4567
4568     if ((i & 1) != 0) {
4569       SDValue ThisElt, LastElt;
4570       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4571       if (LastIsNonZero) {
4572         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4573                               MVT::i16, Op.getOperand(i-1));
4574       }
4575       if (ThisIsNonZero) {
4576         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4577         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4578                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4579         if (LastIsNonZero)
4580           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4581       } else
4582         ThisElt = LastElt;
4583
4584       if (ThisElt.getNode())
4585         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4586                         DAG.getIntPtrConstant(i/2, dl));
4587     }
4588   }
4589
4590   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4591 }
4592
4593 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4594 ///
4595 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4596                                      unsigned NumNonZero, unsigned NumZero,
4597                                      SelectionDAG &DAG,
4598                                      const X86Subtarget* Subtarget,
4599                                      const TargetLowering &TLI) {
4600   if (NumNonZero > 4)
4601     return SDValue();
4602
4603   SDLoc dl(Op);
4604   SDValue V;
4605   bool First = true;
4606   for (unsigned i = 0; i < 8; ++i) {
4607     bool isNonZero = (NonZeros & (1 << i)) != 0;
4608     if (isNonZero) {
4609       if (First) {
4610         if (NumZero)
4611           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4612         else
4613           V = DAG.getUNDEF(MVT::v8i16);
4614         First = false;
4615       }
4616       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4617                       MVT::v8i16, V, Op.getOperand(i),
4618                       DAG.getIntPtrConstant(i, dl));
4619     }
4620   }
4621
4622   return V;
4623 }
4624
4625 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4626 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4627                                      const X86Subtarget *Subtarget,
4628                                      const TargetLowering &TLI) {
4629   // Find all zeroable elements.
4630   std::bitset<4> Zeroable;
4631   for (int i=0; i < 4; ++i) {
4632     SDValue Elt = Op->getOperand(i);
4633     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4634   }
4635   assert(Zeroable.size() - Zeroable.count() > 1 &&
4636          "We expect at least two non-zero elements!");
4637
4638   // We only know how to deal with build_vector nodes where elements are either
4639   // zeroable or extract_vector_elt with constant index.
4640   SDValue FirstNonZero;
4641   unsigned FirstNonZeroIdx;
4642   for (unsigned i=0; i < 4; ++i) {
4643     if (Zeroable[i])
4644       continue;
4645     SDValue Elt = Op->getOperand(i);
4646     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4647         !isa<ConstantSDNode>(Elt.getOperand(1)))
4648       return SDValue();
4649     // Make sure that this node is extracting from a 128-bit vector.
4650     MVT VT = Elt.getOperand(0).getSimpleValueType();
4651     if (!VT.is128BitVector())
4652       return SDValue();
4653     if (!FirstNonZero.getNode()) {
4654       FirstNonZero = Elt;
4655       FirstNonZeroIdx = i;
4656     }
4657   }
4658
4659   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4660   SDValue V1 = FirstNonZero.getOperand(0);
4661   MVT VT = V1.getSimpleValueType();
4662
4663   // See if this build_vector can be lowered as a blend with zero.
4664   SDValue Elt;
4665   unsigned EltMaskIdx, EltIdx;
4666   int Mask[4];
4667   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4668     if (Zeroable[EltIdx]) {
4669       // The zero vector will be on the right hand side.
4670       Mask[EltIdx] = EltIdx+4;
4671       continue;
4672     }
4673
4674     Elt = Op->getOperand(EltIdx);
4675     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4676     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4677     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4678       break;
4679     Mask[EltIdx] = EltIdx;
4680   }
4681
4682   if (EltIdx == 4) {
4683     // Let the shuffle legalizer deal with blend operations.
4684     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4685     if (V1.getSimpleValueType() != VT)
4686       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4687     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4688   }
4689
4690   // See if we can lower this build_vector to a INSERTPS.
4691   if (!Subtarget->hasSSE41())
4692     return SDValue();
4693
4694   SDValue V2 = Elt.getOperand(0);
4695   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4696     V1 = SDValue();
4697
4698   bool CanFold = true;
4699   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4700     if (Zeroable[i])
4701       continue;
4702
4703     SDValue Current = Op->getOperand(i);
4704     SDValue SrcVector = Current->getOperand(0);
4705     if (!V1.getNode())
4706       V1 = SrcVector;
4707     CanFold = SrcVector == V1 &&
4708       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4709   }
4710
4711   if (!CanFold)
4712     return SDValue();
4713
4714   assert(V1.getNode() && "Expected at least two non-zero elements!");
4715   if (V1.getSimpleValueType() != MVT::v4f32)
4716     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4717   if (V2.getSimpleValueType() != MVT::v4f32)
4718     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4719
4720   // Ok, we can emit an INSERTPS instruction.
4721   unsigned ZMask = Zeroable.to_ulong();
4722
4723   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4724   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4725   SDLoc DL(Op);
4726   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4727                                DAG.getIntPtrConstant(InsertPSMask, DL));
4728   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4729 }
4730
4731 /// Return a vector logical shift node.
4732 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4733                          unsigned NumBits, SelectionDAG &DAG,
4734                          const TargetLowering &TLI, SDLoc dl) {
4735   assert(VT.is128BitVector() && "Unknown type for VShift");
4736   MVT ShVT = MVT::v2i64;
4737   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4738   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4739   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4740   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4741   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4742   return DAG.getNode(ISD::BITCAST, dl, VT,
4743                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4744 }
4745
4746 static SDValue
4747 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4748
4749   // Check if the scalar load can be widened into a vector load. And if
4750   // the address is "base + cst" see if the cst can be "absorbed" into
4751   // the shuffle mask.
4752   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4753     SDValue Ptr = LD->getBasePtr();
4754     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4755       return SDValue();
4756     EVT PVT = LD->getValueType(0);
4757     if (PVT != MVT::i32 && PVT != MVT::f32)
4758       return SDValue();
4759
4760     int FI = -1;
4761     int64_t Offset = 0;
4762     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4763       FI = FINode->getIndex();
4764       Offset = 0;
4765     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4766                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4767       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4768       Offset = Ptr.getConstantOperandVal(1);
4769       Ptr = Ptr.getOperand(0);
4770     } else {
4771       return SDValue();
4772     }
4773
4774     // FIXME: 256-bit vector instructions don't require a strict alignment,
4775     // improve this code to support it better.
4776     unsigned RequiredAlign = VT.getSizeInBits()/8;
4777     SDValue Chain = LD->getChain();
4778     // Make sure the stack object alignment is at least 16 or 32.
4779     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4780     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4781       if (MFI->isFixedObjectIndex(FI)) {
4782         // Can't change the alignment. FIXME: It's possible to compute
4783         // the exact stack offset and reference FI + adjust offset instead.
4784         // If someone *really* cares about this. That's the way to implement it.
4785         return SDValue();
4786       } else {
4787         MFI->setObjectAlignment(FI, RequiredAlign);
4788       }
4789     }
4790
4791     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4792     // Ptr + (Offset & ~15).
4793     if (Offset < 0)
4794       return SDValue();
4795     if ((Offset % RequiredAlign) & 3)
4796       return SDValue();
4797     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4798     if (StartOffset) {
4799       SDLoc DL(Ptr);
4800       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4801                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4802     }
4803
4804     int EltNo = (Offset - StartOffset) >> 2;
4805     unsigned NumElems = VT.getVectorNumElements();
4806
4807     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4808     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4809                              LD->getPointerInfo().getWithOffset(StartOffset),
4810                              false, false, false, 0);
4811
4812     SmallVector<int, 8> Mask(NumElems, EltNo);
4813
4814     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4815   }
4816
4817   return SDValue();
4818 }
4819
4820 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4821 /// elements can be replaced by a single large load which has the same value as
4822 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4823 ///
4824 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4825 ///
4826 /// FIXME: we'd also like to handle the case where the last elements are zero
4827 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4828 /// There's even a handy isZeroNode for that purpose.
4829 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4830                                         SDLoc &DL, SelectionDAG &DAG,
4831                                         bool isAfterLegalize) {
4832   unsigned NumElems = Elts.size();
4833
4834   LoadSDNode *LDBase = nullptr;
4835   unsigned LastLoadedElt = -1U;
4836
4837   // For each element in the initializer, see if we've found a load or an undef.
4838   // If we don't find an initial load element, or later load elements are
4839   // non-consecutive, bail out.
4840   for (unsigned i = 0; i < NumElems; ++i) {
4841     SDValue Elt = Elts[i];
4842     // Look through a bitcast.
4843     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4844       Elt = Elt.getOperand(0);
4845     if (!Elt.getNode() ||
4846         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4847       return SDValue();
4848     if (!LDBase) {
4849       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4850         return SDValue();
4851       LDBase = cast<LoadSDNode>(Elt.getNode());
4852       LastLoadedElt = i;
4853       continue;
4854     }
4855     if (Elt.getOpcode() == ISD::UNDEF)
4856       continue;
4857
4858     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4859     EVT LdVT = Elt.getValueType();
4860     // Each loaded element must be the correct fractional portion of the
4861     // requested vector load.
4862     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4863       return SDValue();
4864     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4865       return SDValue();
4866     LastLoadedElt = i;
4867   }
4868
4869   // If we have found an entire vector of loads and undefs, then return a large
4870   // load of the entire vector width starting at the base pointer.  If we found
4871   // consecutive loads for the low half, generate a vzext_load node.
4872   if (LastLoadedElt == NumElems - 1) {
4873     assert(LDBase && "Did not find base load for merging consecutive loads");
4874     EVT EltVT = LDBase->getValueType(0);
4875     // Ensure that the input vector size for the merged loads matches the
4876     // cumulative size of the input elements.
4877     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4878       return SDValue();
4879
4880     if (isAfterLegalize &&
4881         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4882       return SDValue();
4883
4884     SDValue NewLd = SDValue();
4885
4886     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4887                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4888                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4889                         LDBase->getAlignment());
4890
4891     if (LDBase->hasAnyUseOfValue(1)) {
4892       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4893                                      SDValue(LDBase, 1),
4894                                      SDValue(NewLd.getNode(), 1));
4895       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4896       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4897                              SDValue(NewLd.getNode(), 1));
4898     }
4899
4900     return NewLd;
4901   }
4902
4903   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4904   //of a v4i32 / v4f32. It's probably worth generalizing.
4905   EVT EltVT = VT.getVectorElementType();
4906   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4907       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4908     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4909     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4910     SDValue ResNode =
4911         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4912                                 LDBase->getPointerInfo(),
4913                                 LDBase->getAlignment(),
4914                                 false/*isVolatile*/, true/*ReadMem*/,
4915                                 false/*WriteMem*/);
4916
4917     // Make sure the newly-created LOAD is in the same position as LDBase in
4918     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4919     // update uses of LDBase's output chain to use the TokenFactor.
4920     if (LDBase->hasAnyUseOfValue(1)) {
4921       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4922                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4923       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4924       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4925                              SDValue(ResNode.getNode(), 1));
4926     }
4927
4928     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4929   }
4930   return SDValue();
4931 }
4932
4933 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4934 /// to generate a splat value for the following cases:
4935 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4936 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4937 /// a scalar load, or a constant.
4938 /// The VBROADCAST node is returned when a pattern is found,
4939 /// or SDValue() otherwise.
4940 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4941                                     SelectionDAG &DAG) {
4942   // VBROADCAST requires AVX.
4943   // TODO: Splats could be generated for non-AVX CPUs using SSE
4944   // instructions, but there's less potential gain for only 128-bit vectors.
4945   if (!Subtarget->hasAVX())
4946     return SDValue();
4947
4948   MVT VT = Op.getSimpleValueType();
4949   SDLoc dl(Op);
4950
4951   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4952          "Unsupported vector type for broadcast.");
4953
4954   SDValue Ld;
4955   bool ConstSplatVal;
4956
4957   switch (Op.getOpcode()) {
4958     default:
4959       // Unknown pattern found.
4960       return SDValue();
4961
4962     case ISD::BUILD_VECTOR: {
4963       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4964       BitVector UndefElements;
4965       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4966
4967       // We need a splat of a single value to use broadcast, and it doesn't
4968       // make any sense if the value is only in one element of the vector.
4969       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4970         return SDValue();
4971
4972       Ld = Splat;
4973       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4974                        Ld.getOpcode() == ISD::ConstantFP);
4975
4976       // Make sure that all of the users of a non-constant load are from the
4977       // BUILD_VECTOR node.
4978       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4979         return SDValue();
4980       break;
4981     }
4982
4983     case ISD::VECTOR_SHUFFLE: {
4984       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4985
4986       // Shuffles must have a splat mask where the first element is
4987       // broadcasted.
4988       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4989         return SDValue();
4990
4991       SDValue Sc = Op.getOperand(0);
4992       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4993           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4994
4995         if (!Subtarget->hasInt256())
4996           return SDValue();
4997
4998         // Use the register form of the broadcast instruction available on AVX2.
4999         if (VT.getSizeInBits() >= 256)
5000           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5001         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5002       }
5003
5004       Ld = Sc.getOperand(0);
5005       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5006                        Ld.getOpcode() == ISD::ConstantFP);
5007
5008       // The scalar_to_vector node and the suspected
5009       // load node must have exactly one user.
5010       // Constants may have multiple users.
5011
5012       // AVX-512 has register version of the broadcast
5013       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5014         Ld.getValueType().getSizeInBits() >= 32;
5015       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5016           !hasRegVer))
5017         return SDValue();
5018       break;
5019     }
5020   }
5021
5022   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5023   bool IsGE256 = (VT.getSizeInBits() >= 256);
5024
5025   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5026   // instruction to save 8 or more bytes of constant pool data.
5027   // TODO: If multiple splats are generated to load the same constant,
5028   // it may be detrimental to overall size. There needs to be a way to detect
5029   // that condition to know if this is truly a size win.
5030   const Function *F = DAG.getMachineFunction().getFunction();
5031   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5032
5033   // Handle broadcasting a single constant scalar from the constant pool
5034   // into a vector.
5035   // On Sandybridge (no AVX2), it is still better to load a constant vector
5036   // from the constant pool and not to broadcast it from a scalar.
5037   // But override that restriction when optimizing for size.
5038   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5039   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5040     EVT CVT = Ld.getValueType();
5041     assert(!CVT.isVector() && "Must not broadcast a vector type");
5042
5043     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5044     // For size optimization, also splat v2f64 and v2i64, and for size opt
5045     // with AVX2, also splat i8 and i16.
5046     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5047     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5048         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5049       const Constant *C = nullptr;
5050       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5051         C = CI->getConstantIntValue();
5052       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5053         C = CF->getConstantFPValue();
5054
5055       assert(C && "Invalid constant type");
5056
5057       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5058       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5059       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5060       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5061                        MachinePointerInfo::getConstantPool(),
5062                        false, false, false, Alignment);
5063
5064       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5065     }
5066   }
5067
5068   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5069
5070   // Handle AVX2 in-register broadcasts.
5071   if (!IsLoad && Subtarget->hasInt256() &&
5072       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5073     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5074
5075   // The scalar source must be a normal load.
5076   if (!IsLoad)
5077     return SDValue();
5078
5079   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5080       (Subtarget->hasVLX() && ScalarSize == 64))
5081     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5082
5083   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5084   // double since there is no vbroadcastsd xmm
5085   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5086     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5087       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5088   }
5089
5090   // Unsupported broadcast.
5091   return SDValue();
5092 }
5093
5094 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5095 /// underlying vector and index.
5096 ///
5097 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5098 /// index.
5099 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5100                                          SDValue ExtIdx) {
5101   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5102   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5103     return Idx;
5104
5105   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5106   // lowered this:
5107   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5108   // to:
5109   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5110   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5111   //                           undef)
5112   //                       Constant<0>)
5113   // In this case the vector is the extract_subvector expression and the index
5114   // is 2, as specified by the shuffle.
5115   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5116   SDValue ShuffleVec = SVOp->getOperand(0);
5117   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5118   assert(ShuffleVecVT.getVectorElementType() ==
5119          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5120
5121   int ShuffleIdx = SVOp->getMaskElt(Idx);
5122   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5123     ExtractedFromVec = ShuffleVec;
5124     return ShuffleIdx;
5125   }
5126   return Idx;
5127 }
5128
5129 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5130   MVT VT = Op.getSimpleValueType();
5131
5132   // Skip if insert_vec_elt is not supported.
5133   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5134   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5135     return SDValue();
5136
5137   SDLoc DL(Op);
5138   unsigned NumElems = Op.getNumOperands();
5139
5140   SDValue VecIn1;
5141   SDValue VecIn2;
5142   SmallVector<unsigned, 4> InsertIndices;
5143   SmallVector<int, 8> Mask(NumElems, -1);
5144
5145   for (unsigned i = 0; i != NumElems; ++i) {
5146     unsigned Opc = Op.getOperand(i).getOpcode();
5147
5148     if (Opc == ISD::UNDEF)
5149       continue;
5150
5151     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5152       // Quit if more than 1 elements need inserting.
5153       if (InsertIndices.size() > 1)
5154         return SDValue();
5155
5156       InsertIndices.push_back(i);
5157       continue;
5158     }
5159
5160     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5161     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5162     // Quit if non-constant index.
5163     if (!isa<ConstantSDNode>(ExtIdx))
5164       return SDValue();
5165     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5166
5167     // Quit if extracted from vector of different type.
5168     if (ExtractedFromVec.getValueType() != VT)
5169       return SDValue();
5170
5171     if (!VecIn1.getNode())
5172       VecIn1 = ExtractedFromVec;
5173     else if (VecIn1 != ExtractedFromVec) {
5174       if (!VecIn2.getNode())
5175         VecIn2 = ExtractedFromVec;
5176       else if (VecIn2 != ExtractedFromVec)
5177         // Quit if more than 2 vectors to shuffle
5178         return SDValue();
5179     }
5180
5181     if (ExtractedFromVec == VecIn1)
5182       Mask[i] = Idx;
5183     else if (ExtractedFromVec == VecIn2)
5184       Mask[i] = Idx + NumElems;
5185   }
5186
5187   if (!VecIn1.getNode())
5188     return SDValue();
5189
5190   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5191   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5192   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5193     unsigned Idx = InsertIndices[i];
5194     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5195                      DAG.getIntPtrConstant(Idx, DL));
5196   }
5197
5198   return NV;
5199 }
5200
5201 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5202   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5203          Op.getScalarValueSizeInBits() == 1 &&
5204          "Can not convert non-constant vector");
5205   uint64_t Immediate = 0;
5206   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5207     SDValue In = Op.getOperand(idx);
5208     if (In.getOpcode() != ISD::UNDEF)
5209       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5210   }
5211   SDLoc dl(Op);
5212   MVT VT =
5213    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5214   return DAG.getConstant(Immediate, dl, VT);
5215 }
5216 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5217 SDValue
5218 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5219
5220   MVT VT = Op.getSimpleValueType();
5221   assert((VT.getVectorElementType() == MVT::i1) &&
5222          "Unexpected type in LowerBUILD_VECTORvXi1!");
5223
5224   SDLoc dl(Op);
5225   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5226     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5227     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5228     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5229   }
5230
5231   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5232     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5233     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5234     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5235   }
5236
5237   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5238     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5239     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5240       return DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5241     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5242     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5243                         DAG.getIntPtrConstant(0, dl));
5244   }
5245
5246   // Vector has one or more non-const elements
5247   uint64_t Immediate = 0;
5248   SmallVector<unsigned, 16> NonConstIdx;
5249   bool IsSplat = true;
5250   bool HasConstElts = false;
5251   int SplatIdx = -1;
5252   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5253     SDValue In = Op.getOperand(idx);
5254     if (In.getOpcode() == ISD::UNDEF)
5255       continue;
5256     if (!isa<ConstantSDNode>(In)) 
5257       NonConstIdx.push_back(idx);
5258     else {
5259       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5260       HasConstElts = true;
5261     }
5262     if (SplatIdx == -1)
5263       SplatIdx = idx;
5264     else if (In != Op.getOperand(SplatIdx))
5265       IsSplat = false;
5266   }
5267
5268   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5269   if (IsSplat)
5270     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5271                        DAG.getConstant(1, dl, VT),
5272                        DAG.getConstant(0, dl, VT));
5273
5274   // insert elements one by one
5275   SDValue DstVec;
5276   SDValue Imm;
5277   if (Immediate) {
5278     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5279     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5280   }
5281   else if (HasConstElts)
5282     Imm = DAG.getConstant(0, dl, VT);
5283   else 
5284     Imm = DAG.getUNDEF(VT);
5285   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5286     DstVec = DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5287   else {
5288     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5289     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5290                          DAG.getIntPtrConstant(0, dl));
5291   }
5292
5293   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5294     unsigned InsertIdx = NonConstIdx[i];
5295     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5296                          Op.getOperand(InsertIdx),
5297                          DAG.getIntPtrConstant(InsertIdx, dl));
5298   }
5299   return DstVec;
5300 }
5301
5302 /// \brief Return true if \p N implements a horizontal binop and return the
5303 /// operands for the horizontal binop into V0 and V1.
5304 ///
5305 /// This is a helper function of LowerToHorizontalOp().
5306 /// This function checks that the build_vector \p N in input implements a
5307 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5308 /// operation to match.
5309 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5310 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5311 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5312 /// arithmetic sub.
5313 ///
5314 /// This function only analyzes elements of \p N whose indices are
5315 /// in range [BaseIdx, LastIdx).
5316 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5317                               SelectionDAG &DAG,
5318                               unsigned BaseIdx, unsigned LastIdx,
5319                               SDValue &V0, SDValue &V1) {
5320   EVT VT = N->getValueType(0);
5321
5322   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5323   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5324          "Invalid Vector in input!");
5325
5326   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5327   bool CanFold = true;
5328   unsigned ExpectedVExtractIdx = BaseIdx;
5329   unsigned NumElts = LastIdx - BaseIdx;
5330   V0 = DAG.getUNDEF(VT);
5331   V1 = DAG.getUNDEF(VT);
5332
5333   // Check if N implements a horizontal binop.
5334   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5335     SDValue Op = N->getOperand(i + BaseIdx);
5336
5337     // Skip UNDEFs.
5338     if (Op->getOpcode() == ISD::UNDEF) {
5339       // Update the expected vector extract index.
5340       if (i * 2 == NumElts)
5341         ExpectedVExtractIdx = BaseIdx;
5342       ExpectedVExtractIdx += 2;
5343       continue;
5344     }
5345
5346     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5347
5348     if (!CanFold)
5349       break;
5350
5351     SDValue Op0 = Op.getOperand(0);
5352     SDValue Op1 = Op.getOperand(1);
5353
5354     // Try to match the following pattern:
5355     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5356     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5357         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5358         Op0.getOperand(0) == Op1.getOperand(0) &&
5359         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5360         isa<ConstantSDNode>(Op1.getOperand(1)));
5361     if (!CanFold)
5362       break;
5363
5364     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5365     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5366
5367     if (i * 2 < NumElts) {
5368       if (V0.getOpcode() == ISD::UNDEF) {
5369         V0 = Op0.getOperand(0);
5370         if (V0.getValueType() != VT)
5371           return false;
5372       }
5373     } else {
5374       if (V1.getOpcode() == ISD::UNDEF) {
5375         V1 = Op0.getOperand(0);
5376         if (V1.getValueType() != VT)
5377           return false;
5378       }
5379       if (i * 2 == NumElts)
5380         ExpectedVExtractIdx = BaseIdx;
5381     }
5382
5383     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5384     if (I0 == ExpectedVExtractIdx)
5385       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5386     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5387       // Try to match the following dag sequence:
5388       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5389       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5390     } else
5391       CanFold = false;
5392
5393     ExpectedVExtractIdx += 2;
5394   }
5395
5396   return CanFold;
5397 }
5398
5399 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5400 /// a concat_vector.
5401 ///
5402 /// This is a helper function of LowerToHorizontalOp().
5403 /// This function expects two 256-bit vectors called V0 and V1.
5404 /// At first, each vector is split into two separate 128-bit vectors.
5405 /// Then, the resulting 128-bit vectors are used to implement two
5406 /// horizontal binary operations.
5407 ///
5408 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5409 ///
5410 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5411 /// the two new horizontal binop.
5412 /// When Mode is set, the first horizontal binop dag node would take as input
5413 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5414 /// horizontal binop dag node would take as input the lower 128-bit of V1
5415 /// and the upper 128-bit of V1.
5416 ///   Example:
5417 ///     HADD V0_LO, V0_HI
5418 ///     HADD V1_LO, V1_HI
5419 ///
5420 /// Otherwise, the first horizontal binop dag node takes as input the lower
5421 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5422 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5423 ///   Example:
5424 ///     HADD V0_LO, V1_LO
5425 ///     HADD V0_HI, V1_HI
5426 ///
5427 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5428 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5429 /// the upper 128-bits of the result.
5430 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5431                                      SDLoc DL, SelectionDAG &DAG,
5432                                      unsigned X86Opcode, bool Mode,
5433                                      bool isUndefLO, bool isUndefHI) {
5434   EVT VT = V0.getValueType();
5435   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5436          "Invalid nodes in input!");
5437
5438   unsigned NumElts = VT.getVectorNumElements();
5439   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5440   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5441   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5442   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5443   EVT NewVT = V0_LO.getValueType();
5444
5445   SDValue LO = DAG.getUNDEF(NewVT);
5446   SDValue HI = DAG.getUNDEF(NewVT);
5447
5448   if (Mode) {
5449     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5450     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5451       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5452     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5453       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5454   } else {
5455     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5456     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5457                        V1_LO->getOpcode() != ISD::UNDEF))
5458       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5459
5460     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5461                        V1_HI->getOpcode() != ISD::UNDEF))
5462       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5463   }
5464
5465   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5466 }
5467
5468 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5469 /// node.
5470 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5471                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5472   EVT VT = BV->getValueType(0);
5473   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5474       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5475     return SDValue();
5476
5477   SDLoc DL(BV);
5478   unsigned NumElts = VT.getVectorNumElements();
5479   SDValue InVec0 = DAG.getUNDEF(VT);
5480   SDValue InVec1 = DAG.getUNDEF(VT);
5481
5482   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5483           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5484
5485   // Odd-numbered elements in the input build vector are obtained from
5486   // adding two integer/float elements.
5487   // Even-numbered elements in the input build vector are obtained from
5488   // subtracting two integer/float elements.
5489   unsigned ExpectedOpcode = ISD::FSUB;
5490   unsigned NextExpectedOpcode = ISD::FADD;
5491   bool AddFound = false;
5492   bool SubFound = false;
5493
5494   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5495     SDValue Op = BV->getOperand(i);
5496
5497     // Skip 'undef' values.
5498     unsigned Opcode = Op.getOpcode();
5499     if (Opcode == ISD::UNDEF) {
5500       std::swap(ExpectedOpcode, NextExpectedOpcode);
5501       continue;
5502     }
5503
5504     // Early exit if we found an unexpected opcode.
5505     if (Opcode != ExpectedOpcode)
5506       return SDValue();
5507
5508     SDValue Op0 = Op.getOperand(0);
5509     SDValue Op1 = Op.getOperand(1);
5510
5511     // Try to match the following pattern:
5512     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5513     // Early exit if we cannot match that sequence.
5514     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5515         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5516         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5517         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5518         Op0.getOperand(1) != Op1.getOperand(1))
5519       return SDValue();
5520
5521     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5522     if (I0 != i)
5523       return SDValue();
5524
5525     // We found a valid add/sub node. Update the information accordingly.
5526     if (i & 1)
5527       AddFound = true;
5528     else
5529       SubFound = true;
5530
5531     // Update InVec0 and InVec1.
5532     if (InVec0.getOpcode() == ISD::UNDEF) {
5533       InVec0 = Op0.getOperand(0);
5534       if (InVec0.getValueType() != VT)
5535         return SDValue();
5536     }
5537     if (InVec1.getOpcode() == ISD::UNDEF) {
5538       InVec1 = Op1.getOperand(0);
5539       if (InVec1.getValueType() != VT)
5540         return SDValue();
5541     }
5542
5543     // Make sure that operands in input to each add/sub node always
5544     // come from a same pair of vectors.
5545     if (InVec0 != Op0.getOperand(0)) {
5546       if (ExpectedOpcode == ISD::FSUB)
5547         return SDValue();
5548
5549       // FADD is commutable. Try to commute the operands
5550       // and then test again.
5551       std::swap(Op0, Op1);
5552       if (InVec0 != Op0.getOperand(0))
5553         return SDValue();
5554     }
5555
5556     if (InVec1 != Op1.getOperand(0))
5557       return SDValue();
5558
5559     // Update the pair of expected opcodes.
5560     std::swap(ExpectedOpcode, NextExpectedOpcode);
5561   }
5562
5563   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5564   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5565       InVec1.getOpcode() != ISD::UNDEF)
5566     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5567
5568   return SDValue();
5569 }
5570
5571 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5572 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5573                                    const X86Subtarget *Subtarget,
5574                                    SelectionDAG &DAG) {
5575   EVT VT = BV->getValueType(0);
5576   unsigned NumElts = VT.getVectorNumElements();
5577   unsigned NumUndefsLO = 0;
5578   unsigned NumUndefsHI = 0;
5579   unsigned Half = NumElts/2;
5580
5581   // Count the number of UNDEF operands in the build_vector in input.
5582   for (unsigned i = 0, e = Half; i != e; ++i)
5583     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5584       NumUndefsLO++;
5585
5586   for (unsigned i = Half, e = NumElts; i != e; ++i)
5587     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5588       NumUndefsHI++;
5589
5590   // Early exit if this is either a build_vector of all UNDEFs or all the
5591   // operands but one are UNDEF.
5592   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5593     return SDValue();
5594
5595   SDLoc DL(BV);
5596   SDValue InVec0, InVec1;
5597   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5598     // Try to match an SSE3 float HADD/HSUB.
5599     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5600       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5601
5602     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5603       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5604   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5605     // Try to match an SSSE3 integer HADD/HSUB.
5606     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5607       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5608
5609     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5610       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5611   }
5612
5613   if (!Subtarget->hasAVX())
5614     return SDValue();
5615
5616   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5617     // Try to match an AVX horizontal add/sub of packed single/double
5618     // precision floating point values from 256-bit vectors.
5619     SDValue InVec2, InVec3;
5620     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5621         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5622         ((InVec0.getOpcode() == ISD::UNDEF ||
5623           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5624         ((InVec1.getOpcode() == ISD::UNDEF ||
5625           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5626       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5627
5628     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5629         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5630         ((InVec0.getOpcode() == ISD::UNDEF ||
5631           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5632         ((InVec1.getOpcode() == ISD::UNDEF ||
5633           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5634       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5635   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5636     // Try to match an AVX2 horizontal add/sub of signed integers.
5637     SDValue InVec2, InVec3;
5638     unsigned X86Opcode;
5639     bool CanFold = true;
5640
5641     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5642         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5643         ((InVec0.getOpcode() == ISD::UNDEF ||
5644           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5645         ((InVec1.getOpcode() == ISD::UNDEF ||
5646           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5647       X86Opcode = X86ISD::HADD;
5648     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5649         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5650         ((InVec0.getOpcode() == ISD::UNDEF ||
5651           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5652         ((InVec1.getOpcode() == ISD::UNDEF ||
5653           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5654       X86Opcode = X86ISD::HSUB;
5655     else
5656       CanFold = false;
5657
5658     if (CanFold) {
5659       // Fold this build_vector into a single horizontal add/sub.
5660       // Do this only if the target has AVX2.
5661       if (Subtarget->hasAVX2())
5662         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5663
5664       // Do not try to expand this build_vector into a pair of horizontal
5665       // add/sub if we can emit a pair of scalar add/sub.
5666       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5667         return SDValue();
5668
5669       // Convert this build_vector into a pair of horizontal binop followed by
5670       // a concat vector.
5671       bool isUndefLO = NumUndefsLO == Half;
5672       bool isUndefHI = NumUndefsHI == Half;
5673       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5674                                    isUndefLO, isUndefHI);
5675     }
5676   }
5677
5678   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5679        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5680     unsigned X86Opcode;
5681     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5682       X86Opcode = X86ISD::HADD;
5683     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5684       X86Opcode = X86ISD::HSUB;
5685     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5686       X86Opcode = X86ISD::FHADD;
5687     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5688       X86Opcode = X86ISD::FHSUB;
5689     else
5690       return SDValue();
5691
5692     // Don't try to expand this build_vector into a pair of horizontal add/sub
5693     // if we can simply emit a pair of scalar add/sub.
5694     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5695       return SDValue();
5696
5697     // Convert this build_vector into two horizontal add/sub followed by
5698     // a concat vector.
5699     bool isUndefLO = NumUndefsLO == Half;
5700     bool isUndefHI = NumUndefsHI == Half;
5701     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5702                                  isUndefLO, isUndefHI);
5703   }
5704
5705   return SDValue();
5706 }
5707
5708 SDValue
5709 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5710   SDLoc dl(Op);
5711
5712   MVT VT = Op.getSimpleValueType();
5713   MVT ExtVT = VT.getVectorElementType();
5714   unsigned NumElems = Op.getNumOperands();
5715
5716   // Generate vectors for predicate vectors.
5717   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5718     return LowerBUILD_VECTORvXi1(Op, DAG);
5719
5720   // Vectors containing all zeros can be matched by pxor and xorps later
5721   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5722     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5723     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5724     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5725       return Op;
5726
5727     return getZeroVector(VT, Subtarget, DAG, dl);
5728   }
5729
5730   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5731   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5732   // vpcmpeqd on 256-bit vectors.
5733   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5734     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5735       return Op;
5736
5737     if (!VT.is512BitVector())
5738       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5739   }
5740
5741   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5742   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5743     return AddSub;
5744   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5745     return HorizontalOp;
5746   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5747     return Broadcast;
5748
5749   unsigned EVTBits = ExtVT.getSizeInBits();
5750
5751   unsigned NumZero  = 0;
5752   unsigned NumNonZero = 0;
5753   unsigned NonZeros = 0;
5754   bool IsAllConstants = true;
5755   SmallSet<SDValue, 8> Values;
5756   for (unsigned i = 0; i < NumElems; ++i) {
5757     SDValue Elt = Op.getOperand(i);
5758     if (Elt.getOpcode() == ISD::UNDEF)
5759       continue;
5760     Values.insert(Elt);
5761     if (Elt.getOpcode() != ISD::Constant &&
5762         Elt.getOpcode() != ISD::ConstantFP)
5763       IsAllConstants = false;
5764     if (X86::isZeroNode(Elt))
5765       NumZero++;
5766     else {
5767       NonZeros |= (1 << i);
5768       NumNonZero++;
5769     }
5770   }
5771
5772   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5773   if (NumNonZero == 0)
5774     return DAG.getUNDEF(VT);
5775
5776   // Special case for single non-zero, non-undef, element.
5777   if (NumNonZero == 1) {
5778     unsigned Idx = countTrailingZeros(NonZeros);
5779     SDValue Item = Op.getOperand(Idx);
5780
5781     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5782     // the value are obviously zero, truncate the value to i32 and do the
5783     // insertion that way.  Only do this if the value is non-constant or if the
5784     // value is a constant being inserted into element 0.  It is cheaper to do
5785     // a constant pool load than it is to do a movd + shuffle.
5786     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5787         (!IsAllConstants || Idx == 0)) {
5788       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5789         // Handle SSE only.
5790         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5791         EVT VecVT = MVT::v4i32;
5792
5793         // Truncate the value (which may itself be a constant) to i32, and
5794         // convert it to a vector with movd (S2V+shuffle to zero extend).
5795         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5796         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5797         return DAG.getNode(
5798             ISD::BITCAST, dl, VT,
5799             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5800       }
5801     }
5802
5803     // If we have a constant or non-constant insertion into the low element of
5804     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5805     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5806     // depending on what the source datatype is.
5807     if (Idx == 0) {
5808       if (NumZero == 0)
5809         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5810
5811       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5812           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5813         if (VT.is512BitVector()) {
5814           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5815           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5816                              Item, DAG.getIntPtrConstant(0, dl));
5817         }
5818         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5819                "Expected an SSE value type!");
5820         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5821         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5822         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5823       }
5824
5825       // We can't directly insert an i8 or i16 into a vector, so zero extend
5826       // it to i32 first.
5827       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5828         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5829         if (VT.is256BitVector()) {
5830           if (Subtarget->hasAVX()) {
5831             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5832             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5833           } else {
5834             // Without AVX, we need to extend to a 128-bit vector and then
5835             // insert into the 256-bit vector.
5836             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5837             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5838             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5839           }
5840         } else {
5841           assert(VT.is128BitVector() && "Expected an SSE value type!");
5842           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5843           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5844         }
5845         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5846       }
5847     }
5848
5849     // Is it a vector logical left shift?
5850     if (NumElems == 2 && Idx == 1 &&
5851         X86::isZeroNode(Op.getOperand(0)) &&
5852         !X86::isZeroNode(Op.getOperand(1))) {
5853       unsigned NumBits = VT.getSizeInBits();
5854       return getVShift(true, VT,
5855                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5856                                    VT, Op.getOperand(1)),
5857                        NumBits/2, DAG, *this, dl);
5858     }
5859
5860     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5861       return SDValue();
5862
5863     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5864     // is a non-constant being inserted into an element other than the low one,
5865     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5866     // movd/movss) to move this into the low element, then shuffle it into
5867     // place.
5868     if (EVTBits == 32) {
5869       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5870       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5871     }
5872   }
5873
5874   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5875   if (Values.size() == 1) {
5876     if (EVTBits == 32) {
5877       // Instead of a shuffle like this:
5878       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5879       // Check if it's possible to issue this instead.
5880       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5881       unsigned Idx = countTrailingZeros(NonZeros);
5882       SDValue Item = Op.getOperand(Idx);
5883       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5884         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5885     }
5886     return SDValue();
5887   }
5888
5889   // A vector full of immediates; various special cases are already
5890   // handled, so this is best done with a single constant-pool load.
5891   if (IsAllConstants)
5892     return SDValue();
5893
5894   // For AVX-length vectors, see if we can use a vector load to get all of the
5895   // elements, otherwise build the individual 128-bit pieces and use
5896   // shuffles to put them in place.
5897   if (VT.is256BitVector() || VT.is512BitVector()) {
5898     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5899
5900     // Check for a build vector of consecutive loads.
5901     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5902       return LD;
5903
5904     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5905
5906     // Build both the lower and upper subvector.
5907     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5908                                 makeArrayRef(&V[0], NumElems/2));
5909     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5910                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5911
5912     // Recreate the wider vector with the lower and upper part.
5913     if (VT.is256BitVector())
5914       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5915     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5916   }
5917
5918   // Let legalizer expand 2-wide build_vectors.
5919   if (EVTBits == 64) {
5920     if (NumNonZero == 1) {
5921       // One half is zero or undef.
5922       unsigned Idx = countTrailingZeros(NonZeros);
5923       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5924                                  Op.getOperand(Idx));
5925       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5926     }
5927     return SDValue();
5928   }
5929
5930   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5931   if (EVTBits == 8 && NumElems == 16)
5932     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5933                                         Subtarget, *this))
5934       return V;
5935
5936   if (EVTBits == 16 && NumElems == 8)
5937     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5938                                       Subtarget, *this))
5939       return V;
5940
5941   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5942   if (EVTBits == 32 && NumElems == 4)
5943     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5944       return V;
5945
5946   // If element VT is == 32 bits, turn it into a number of shuffles.
5947   SmallVector<SDValue, 8> V(NumElems);
5948   if (NumElems == 4 && NumZero > 0) {
5949     for (unsigned i = 0; i < 4; ++i) {
5950       bool isZero = !(NonZeros & (1 << i));
5951       if (isZero)
5952         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5953       else
5954         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5955     }
5956
5957     for (unsigned i = 0; i < 2; ++i) {
5958       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5959         default: break;
5960         case 0:
5961           V[i] = V[i*2];  // Must be a zero vector.
5962           break;
5963         case 1:
5964           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5965           break;
5966         case 2:
5967           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5968           break;
5969         case 3:
5970           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5971           break;
5972       }
5973     }
5974
5975     bool Reverse1 = (NonZeros & 0x3) == 2;
5976     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5977     int MaskVec[] = {
5978       Reverse1 ? 1 : 0,
5979       Reverse1 ? 0 : 1,
5980       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5981       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5982     };
5983     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5984   }
5985
5986   if (Values.size() > 1 && VT.is128BitVector()) {
5987     // Check for a build vector of consecutive loads.
5988     for (unsigned i = 0; i < NumElems; ++i)
5989       V[i] = Op.getOperand(i);
5990
5991     // Check for elements which are consecutive loads.
5992     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5993       return LD;
5994
5995     // Check for a build vector from mostly shuffle plus few inserting.
5996     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5997       return Sh;
5998
5999     // For SSE 4.1, use insertps to put the high elements into the low element.
6000     if (Subtarget->hasSSE41()) {
6001       SDValue Result;
6002       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6003         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6004       else
6005         Result = DAG.getUNDEF(VT);
6006
6007       for (unsigned i = 1; i < NumElems; ++i) {
6008         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6009         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6010                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6011       }
6012       return Result;
6013     }
6014
6015     // Otherwise, expand into a number of unpckl*, start by extending each of
6016     // our (non-undef) elements to the full vector width with the element in the
6017     // bottom slot of the vector (which generates no code for SSE).
6018     for (unsigned i = 0; i < NumElems; ++i) {
6019       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6020         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6021       else
6022         V[i] = DAG.getUNDEF(VT);
6023     }
6024
6025     // Next, we iteratively mix elements, e.g. for v4f32:
6026     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6027     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6028     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6029     unsigned EltStride = NumElems >> 1;
6030     while (EltStride != 0) {
6031       for (unsigned i = 0; i < EltStride; ++i) {
6032         // If V[i+EltStride] is undef and this is the first round of mixing,
6033         // then it is safe to just drop this shuffle: V[i] is already in the
6034         // right place, the one element (since it's the first round) being
6035         // inserted as undef can be dropped.  This isn't safe for successive
6036         // rounds because they will permute elements within both vectors.
6037         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6038             EltStride == NumElems/2)
6039           continue;
6040
6041         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6042       }
6043       EltStride >>= 1;
6044     }
6045     return V[0];
6046   }
6047   return SDValue();
6048 }
6049
6050 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6051 // to create 256-bit vectors from two other 128-bit ones.
6052 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6053   SDLoc dl(Op);
6054   MVT ResVT = Op.getSimpleValueType();
6055
6056   assert((ResVT.is256BitVector() ||
6057           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6058
6059   SDValue V1 = Op.getOperand(0);
6060   SDValue V2 = Op.getOperand(1);
6061   unsigned NumElems = ResVT.getVectorNumElements();
6062   if (ResVT.is256BitVector())
6063     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6064
6065   if (Op.getNumOperands() == 4) {
6066     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6067                                 ResVT.getVectorNumElements()/2);
6068     SDValue V3 = Op.getOperand(2);
6069     SDValue V4 = Op.getOperand(3);
6070     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6071       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6072   }
6073   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6074 }
6075
6076 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6077                                        const X86Subtarget *Subtarget,
6078                                        SelectionDAG & DAG) {
6079   SDLoc dl(Op);
6080   MVT ResVT = Op.getSimpleValueType();
6081   unsigned NumOfOperands = Op.getNumOperands();
6082
6083   assert(isPowerOf2_32(NumOfOperands) &&
6084          "Unexpected number of operands in CONCAT_VECTORS");
6085
6086   if (NumOfOperands > 2) {
6087     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6088                                   ResVT.getVectorNumElements()/2);
6089     SmallVector<SDValue, 2> Ops;
6090     for (unsigned i = 0; i < NumOfOperands/2; i++)
6091       Ops.push_back(Op.getOperand(i));
6092     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6093     Ops.clear();
6094     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6095       Ops.push_back(Op.getOperand(i));
6096     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6097     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6098   }
6099
6100   SDValue V1 = Op.getOperand(0);
6101   SDValue V2 = Op.getOperand(1);
6102   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6103   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6104
6105   if (IsZeroV1 && IsZeroV2)
6106     return getZeroVector(ResVT, Subtarget, DAG, dl);
6107
6108   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6109   SDValue Undef = DAG.getUNDEF(ResVT);
6110   unsigned NumElems = ResVT.getVectorNumElements();
6111   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6112
6113   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6114   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6115   if (IsZeroV1)
6116     return V2;
6117
6118   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6119   // Zero the upper bits of V1
6120   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6121   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6122   if (IsZeroV2)
6123     return V1;
6124   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6125 }
6126
6127 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6128                                    const X86Subtarget *Subtarget,
6129                                    SelectionDAG &DAG) {
6130   MVT VT = Op.getSimpleValueType();
6131   if (VT.getVectorElementType() == MVT::i1)
6132     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6133
6134   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6135          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6136           Op.getNumOperands() == 4)));
6137
6138   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6139   // from two other 128-bit ones.
6140
6141   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6142   return LowerAVXCONCAT_VECTORS(Op, DAG);
6143 }
6144
6145
6146 //===----------------------------------------------------------------------===//
6147 // Vector shuffle lowering
6148 //
6149 // This is an experimental code path for lowering vector shuffles on x86. It is
6150 // designed to handle arbitrary vector shuffles and blends, gracefully
6151 // degrading performance as necessary. It works hard to recognize idiomatic
6152 // shuffles and lower them to optimal instruction patterns without leaving
6153 // a framework that allows reasonably efficient handling of all vector shuffle
6154 // patterns.
6155 //===----------------------------------------------------------------------===//
6156
6157 /// \brief Tiny helper function to identify a no-op mask.
6158 ///
6159 /// This is a somewhat boring predicate function. It checks whether the mask
6160 /// array input, which is assumed to be a single-input shuffle mask of the kind
6161 /// used by the X86 shuffle instructions (not a fully general
6162 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6163 /// in-place shuffle are 'no-op's.
6164 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6165   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6166     if (Mask[i] != -1 && Mask[i] != i)
6167       return false;
6168   return true;
6169 }
6170
6171 /// \brief Helper function to classify a mask as a single-input mask.
6172 ///
6173 /// This isn't a generic single-input test because in the vector shuffle
6174 /// lowering we canonicalize single inputs to be the first input operand. This
6175 /// means we can more quickly test for a single input by only checking whether
6176 /// an input from the second operand exists. We also assume that the size of
6177 /// mask corresponds to the size of the input vectors which isn't true in the
6178 /// fully general case.
6179 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6180   for (int M : Mask)
6181     if (M >= (int)Mask.size())
6182       return false;
6183   return true;
6184 }
6185
6186 /// \brief Test whether there are elements crossing 128-bit lanes in this
6187 /// shuffle mask.
6188 ///
6189 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6190 /// and we routinely test for these.
6191 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6192   int LaneSize = 128 / VT.getScalarSizeInBits();
6193   int Size = Mask.size();
6194   for (int i = 0; i < Size; ++i)
6195     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6196       return true;
6197   return false;
6198 }
6199
6200 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6201 ///
6202 /// This checks a shuffle mask to see if it is performing the same
6203 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6204 /// that it is also not lane-crossing. It may however involve a blend from the
6205 /// same lane of a second vector.
6206 ///
6207 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6208 /// non-trivial to compute in the face of undef lanes. The representation is
6209 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6210 /// entries from both V1 and V2 inputs to the wider mask.
6211 static bool
6212 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6213                                 SmallVectorImpl<int> &RepeatedMask) {
6214   int LaneSize = 128 / VT.getScalarSizeInBits();
6215   RepeatedMask.resize(LaneSize, -1);
6216   int Size = Mask.size();
6217   for (int i = 0; i < Size; ++i) {
6218     if (Mask[i] < 0)
6219       continue;
6220     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6221       // This entry crosses lanes, so there is no way to model this shuffle.
6222       return false;
6223
6224     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6225     if (RepeatedMask[i % LaneSize] == -1)
6226       // This is the first non-undef entry in this slot of a 128-bit lane.
6227       RepeatedMask[i % LaneSize] =
6228           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6229     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6230       // Found a mismatch with the repeated mask.
6231       return false;
6232   }
6233   return true;
6234 }
6235
6236 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6237 /// arguments.
6238 ///
6239 /// This is a fast way to test a shuffle mask against a fixed pattern:
6240 ///
6241 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6242 ///
6243 /// It returns true if the mask is exactly as wide as the argument list, and
6244 /// each element of the mask is either -1 (signifying undef) or the value given
6245 /// in the argument.
6246 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6247                                 ArrayRef<int> ExpectedMask) {
6248   if (Mask.size() != ExpectedMask.size())
6249     return false;
6250
6251   int Size = Mask.size();
6252
6253   // If the values are build vectors, we can look through them to find
6254   // equivalent inputs that make the shuffles equivalent.
6255   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6256   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6257
6258   for (int i = 0; i < Size; ++i)
6259     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6260       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6261       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6262       if (!MaskBV || !ExpectedBV ||
6263           MaskBV->getOperand(Mask[i] % Size) !=
6264               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6265         return false;
6266     }
6267
6268   return true;
6269 }
6270
6271 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6272 ///
6273 /// This helper function produces an 8-bit shuffle immediate corresponding to
6274 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6275 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6276 /// example.
6277 ///
6278 /// NB: We rely heavily on "undef" masks preserving the input lane.
6279 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6280                                           SelectionDAG &DAG) {
6281   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6282   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6283   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6284   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6285   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6286
6287   unsigned Imm = 0;
6288   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6289   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6290   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6291   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6292   return DAG.getConstant(Imm, DL, MVT::i8);
6293 }
6294
6295 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6296 ///
6297 /// This is used as a fallback approach when first class blend instructions are
6298 /// unavailable. Currently it is only suitable for integer vectors, but could
6299 /// be generalized for floating point vectors if desirable.
6300 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6301                                             SDValue V2, ArrayRef<int> Mask,
6302                                             SelectionDAG &DAG) {
6303   assert(VT.isInteger() && "Only supports integer vector types!");
6304   MVT EltVT = VT.getScalarType();
6305   int NumEltBits = EltVT.getSizeInBits();
6306   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6307   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6308                                     EltVT);
6309   SmallVector<SDValue, 16> MaskOps;
6310   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6311     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6312       return SDValue(); // Shuffled input!
6313     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6314   }
6315
6316   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6317   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6318   // We have to cast V2 around.
6319   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6320   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6321                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6322                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6323                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6324   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6325 }
6326
6327 /// \brief Try to emit a blend instruction for a shuffle.
6328 ///
6329 /// This doesn't do any checks for the availability of instructions for blending
6330 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6331 /// be matched in the backend with the type given. What it does check for is
6332 /// that the shuffle mask is in fact a blend.
6333 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6334                                          SDValue V2, ArrayRef<int> Mask,
6335                                          const X86Subtarget *Subtarget,
6336                                          SelectionDAG &DAG) {
6337   unsigned BlendMask = 0;
6338   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6339     if (Mask[i] >= Size) {
6340       if (Mask[i] != i + Size)
6341         return SDValue(); // Shuffled V2 input!
6342       BlendMask |= 1u << i;
6343       continue;
6344     }
6345     if (Mask[i] >= 0 && Mask[i] != i)
6346       return SDValue(); // Shuffled V1 input!
6347   }
6348   switch (VT.SimpleTy) {
6349   case MVT::v2f64:
6350   case MVT::v4f32:
6351   case MVT::v4f64:
6352   case MVT::v8f32:
6353     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6354                        DAG.getConstant(BlendMask, DL, MVT::i8));
6355
6356   case MVT::v4i64:
6357   case MVT::v8i32:
6358     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6359     // FALLTHROUGH
6360   case MVT::v2i64:
6361   case MVT::v4i32:
6362     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6363     // that instruction.
6364     if (Subtarget->hasAVX2()) {
6365       // Scale the blend by the number of 32-bit dwords per element.
6366       int Scale =  VT.getScalarSizeInBits() / 32;
6367       BlendMask = 0;
6368       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6369         if (Mask[i] >= Size)
6370           for (int j = 0; j < Scale; ++j)
6371             BlendMask |= 1u << (i * Scale + j);
6372
6373       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6374       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6375       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6376       return DAG.getNode(ISD::BITCAST, DL, VT,
6377                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6378                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6379     }
6380     // FALLTHROUGH
6381   case MVT::v8i16: {
6382     // For integer shuffles we need to expand the mask and cast the inputs to
6383     // v8i16s prior to blending.
6384     int Scale = 8 / VT.getVectorNumElements();
6385     BlendMask = 0;
6386     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6387       if (Mask[i] >= Size)
6388         for (int j = 0; j < Scale; ++j)
6389           BlendMask |= 1u << (i * Scale + j);
6390
6391     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6392     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6393     return DAG.getNode(ISD::BITCAST, DL, VT,
6394                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6395                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6396   }
6397
6398   case MVT::v16i16: {
6399     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6400     SmallVector<int, 8> RepeatedMask;
6401     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6402       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6403       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6404       BlendMask = 0;
6405       for (int i = 0; i < 8; ++i)
6406         if (RepeatedMask[i] >= 16)
6407           BlendMask |= 1u << i;
6408       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6409                          DAG.getConstant(BlendMask, DL, MVT::i8));
6410     }
6411   }
6412     // FALLTHROUGH
6413   case MVT::v16i8:
6414   case MVT::v32i8: {
6415     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6416            "256-bit byte-blends require AVX2 support!");
6417
6418     // Scale the blend by the number of bytes per element.
6419     int Scale = VT.getScalarSizeInBits() / 8;
6420
6421     // This form of blend is always done on bytes. Compute the byte vector
6422     // type.
6423     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6424
6425     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6426     // mix of LLVM's code generator and the x86 backend. We tell the code
6427     // generator that boolean values in the elements of an x86 vector register
6428     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6429     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6430     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6431     // of the element (the remaining are ignored) and 0 in that high bit would
6432     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6433     // the LLVM model for boolean values in vector elements gets the relevant
6434     // bit set, it is set backwards and over constrained relative to x86's
6435     // actual model.
6436     SmallVector<SDValue, 32> VSELECTMask;
6437     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6438       for (int j = 0; j < Scale; ++j)
6439         VSELECTMask.push_back(
6440             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6441                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6442                                           MVT::i8));
6443
6444     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6445     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6446     return DAG.getNode(
6447         ISD::BITCAST, DL, VT,
6448         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6449                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6450                     V1, V2));
6451   }
6452
6453   default:
6454     llvm_unreachable("Not a supported integer vector type!");
6455   }
6456 }
6457
6458 /// \brief Try to lower as a blend of elements from two inputs followed by
6459 /// a single-input permutation.
6460 ///
6461 /// This matches the pattern where we can blend elements from two inputs and
6462 /// then reduce the shuffle to a single-input permutation.
6463 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6464                                                    SDValue V2,
6465                                                    ArrayRef<int> Mask,
6466                                                    SelectionDAG &DAG) {
6467   // We build up the blend mask while checking whether a blend is a viable way
6468   // to reduce the shuffle.
6469   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6470   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6471
6472   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6473     if (Mask[i] < 0)
6474       continue;
6475
6476     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6477
6478     if (BlendMask[Mask[i] % Size] == -1)
6479       BlendMask[Mask[i] % Size] = Mask[i];
6480     else if (BlendMask[Mask[i] % Size] != Mask[i])
6481       return SDValue(); // Can't blend in the needed input!
6482
6483     PermuteMask[i] = Mask[i] % Size;
6484   }
6485
6486   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6487   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6488 }
6489
6490 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6491 /// blends and permutes.
6492 ///
6493 /// This matches the extremely common pattern for handling combined
6494 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6495 /// operations. It will try to pick the best arrangement of shuffles and
6496 /// blends.
6497 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6498                                                           SDValue V1,
6499                                                           SDValue V2,
6500                                                           ArrayRef<int> Mask,
6501                                                           SelectionDAG &DAG) {
6502   // Shuffle the input elements into the desired positions in V1 and V2 and
6503   // blend them together.
6504   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6505   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6506   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6507   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6508     if (Mask[i] >= 0 && Mask[i] < Size) {
6509       V1Mask[i] = Mask[i];
6510       BlendMask[i] = i;
6511     } else if (Mask[i] >= Size) {
6512       V2Mask[i] = Mask[i] - Size;
6513       BlendMask[i] = i + Size;
6514     }
6515
6516   // Try to lower with the simpler initial blend strategy unless one of the
6517   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6518   // shuffle may be able to fold with a load or other benefit. However, when
6519   // we'll have to do 2x as many shuffles in order to achieve this, blending
6520   // first is a better strategy.
6521   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6522     if (SDValue BlendPerm =
6523             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6524       return BlendPerm;
6525
6526   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6527   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6528   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6529 }
6530
6531 /// \brief Try to lower a vector shuffle as a byte rotation.
6532 ///
6533 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6534 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6535 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6536 /// try to generically lower a vector shuffle through such an pattern. It
6537 /// does not check for the profitability of lowering either as PALIGNR or
6538 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6539 /// This matches shuffle vectors that look like:
6540 ///
6541 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6542 ///
6543 /// Essentially it concatenates V1 and V2, shifts right by some number of
6544 /// elements, and takes the low elements as the result. Note that while this is
6545 /// specified as a *right shift* because x86 is little-endian, it is a *left
6546 /// rotate* of the vector lanes.
6547 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6548                                               SDValue V2,
6549                                               ArrayRef<int> Mask,
6550                                               const X86Subtarget *Subtarget,
6551                                               SelectionDAG &DAG) {
6552   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6553
6554   int NumElts = Mask.size();
6555   int NumLanes = VT.getSizeInBits() / 128;
6556   int NumLaneElts = NumElts / NumLanes;
6557
6558   // We need to detect various ways of spelling a rotation:
6559   //   [11, 12, 13, 14, 15,  0,  1,  2]
6560   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6561   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6562   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6563   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6564   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6565   int Rotation = 0;
6566   SDValue Lo, Hi;
6567   for (int l = 0; l < NumElts; l += NumLaneElts) {
6568     for (int i = 0; i < NumLaneElts; ++i) {
6569       if (Mask[l + i] == -1)
6570         continue;
6571       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6572
6573       // Get the mod-Size index and lane correct it.
6574       int LaneIdx = (Mask[l + i] % NumElts) - l;
6575       // Make sure it was in this lane.
6576       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6577         return SDValue();
6578
6579       // Determine where a rotated vector would have started.
6580       int StartIdx = i - LaneIdx;
6581       if (StartIdx == 0)
6582         // The identity rotation isn't interesting, stop.
6583         return SDValue();
6584
6585       // If we found the tail of a vector the rotation must be the missing
6586       // front. If we found the head of a vector, it must be how much of the
6587       // head.
6588       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6589
6590       if (Rotation == 0)
6591         Rotation = CandidateRotation;
6592       else if (Rotation != CandidateRotation)
6593         // The rotations don't match, so we can't match this mask.
6594         return SDValue();
6595
6596       // Compute which value this mask is pointing at.
6597       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6598
6599       // Compute which of the two target values this index should be assigned
6600       // to. This reflects whether the high elements are remaining or the low
6601       // elements are remaining.
6602       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6603
6604       // Either set up this value if we've not encountered it before, or check
6605       // that it remains consistent.
6606       if (!TargetV)
6607         TargetV = MaskV;
6608       else if (TargetV != MaskV)
6609         // This may be a rotation, but it pulls from the inputs in some
6610         // unsupported interleaving.
6611         return SDValue();
6612     }
6613   }
6614
6615   // Check that we successfully analyzed the mask, and normalize the results.
6616   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6617   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6618   if (!Lo)
6619     Lo = Hi;
6620   else if (!Hi)
6621     Hi = Lo;
6622
6623   // The actual rotate instruction rotates bytes, so we need to scale the
6624   // rotation based on how many bytes are in the vector lane.
6625   int Scale = 16 / NumLaneElts;
6626
6627   // SSSE3 targets can use the palignr instruction.
6628   if (Subtarget->hasSSSE3()) {
6629     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6630     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6631     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6632     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6633
6634     return DAG.getNode(ISD::BITCAST, DL, VT,
6635                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6636                                    DAG.getConstant(Rotation * Scale, DL,
6637                                                    MVT::i8)));
6638   }
6639
6640   assert(VT.getSizeInBits() == 128 &&
6641          "Rotate-based lowering only supports 128-bit lowering!");
6642   assert(Mask.size() <= 16 &&
6643          "Can shuffle at most 16 bytes in a 128-bit vector!");
6644
6645   // Default SSE2 implementation
6646   int LoByteShift = 16 - Rotation * Scale;
6647   int HiByteShift = Rotation * Scale;
6648
6649   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6650   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6651   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6652
6653   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6654                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6655   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6656                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6657   return DAG.getNode(ISD::BITCAST, DL, VT,
6658                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6659 }
6660
6661 /// \brief Compute whether each element of a shuffle is zeroable.
6662 ///
6663 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6664 /// Either it is an undef element in the shuffle mask, the element of the input
6665 /// referenced is undef, or the element of the input referenced is known to be
6666 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6667 /// as many lanes with this technique as possible to simplify the remaining
6668 /// shuffle.
6669 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6670                                                      SDValue V1, SDValue V2) {
6671   SmallBitVector Zeroable(Mask.size(), false);
6672
6673   while (V1.getOpcode() == ISD::BITCAST)
6674     V1 = V1->getOperand(0);
6675   while (V2.getOpcode() == ISD::BITCAST)
6676     V2 = V2->getOperand(0);
6677
6678   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6679   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6680
6681   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6682     int M = Mask[i];
6683     // Handle the easy cases.
6684     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6685       Zeroable[i] = true;
6686       continue;
6687     }
6688
6689     // If this is an index into a build_vector node (which has the same number
6690     // of elements), dig out the input value and use it.
6691     SDValue V = M < Size ? V1 : V2;
6692     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6693       continue;
6694
6695     SDValue Input = V.getOperand(M % Size);
6696     // The UNDEF opcode check really should be dead code here, but not quite
6697     // worth asserting on (it isn't invalid, just unexpected).
6698     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6699       Zeroable[i] = true;
6700   }
6701
6702   return Zeroable;
6703 }
6704
6705 /// \brief Try to emit a bitmask instruction for a shuffle.
6706 ///
6707 /// This handles cases where we can model a blend exactly as a bitmask due to
6708 /// one of the inputs being zeroable.
6709 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6710                                            SDValue V2, ArrayRef<int> Mask,
6711                                            SelectionDAG &DAG) {
6712   MVT EltVT = VT.getScalarType();
6713   int NumEltBits = EltVT.getSizeInBits();
6714   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6715   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6716   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6717                                     IntEltVT);
6718   if (EltVT.isFloatingPoint()) {
6719     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6720     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6721   }
6722   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6723   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6724   SDValue V;
6725   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6726     if (Zeroable[i])
6727       continue;
6728     if (Mask[i] % Size != i)
6729       return SDValue(); // Not a blend.
6730     if (!V)
6731       V = Mask[i] < Size ? V1 : V2;
6732     else if (V != (Mask[i] < Size ? V1 : V2))
6733       return SDValue(); // Can only let one input through the mask.
6734
6735     VMaskOps[i] = AllOnes;
6736   }
6737   if (!V)
6738     return SDValue(); // No non-zeroable elements!
6739
6740   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6741   V = DAG.getNode(VT.isFloatingPoint()
6742                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6743                   DL, VT, V, VMask);
6744   return V;
6745 }
6746
6747 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6748 ///
6749 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6750 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6751 /// matches elements from one of the input vectors shuffled to the left or
6752 /// right with zeroable elements 'shifted in'. It handles both the strictly
6753 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6754 /// quad word lane.
6755 ///
6756 /// PSHL : (little-endian) left bit shift.
6757 /// [ zz, 0, zz,  2 ]
6758 /// [ -1, 4, zz, -1 ]
6759 /// PSRL : (little-endian) right bit shift.
6760 /// [  1, zz,  3, zz]
6761 /// [ -1, -1,  7, zz]
6762 /// PSLLDQ : (little-endian) left byte shift
6763 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6764 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6765 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6766 /// PSRLDQ : (little-endian) right byte shift
6767 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6768 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6769 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6770 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6771                                          SDValue V2, ArrayRef<int> Mask,
6772                                          SelectionDAG &DAG) {
6773   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6774
6775   int Size = Mask.size();
6776   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6777
6778   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6779     for (int i = 0; i < Size; i += Scale)
6780       for (int j = 0; j < Shift; ++j)
6781         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6782           return false;
6783
6784     return true;
6785   };
6786
6787   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6788     for (int i = 0; i != Size; i += Scale) {
6789       unsigned Pos = Left ? i + Shift : i;
6790       unsigned Low = Left ? i : i + Shift;
6791       unsigned Len = Scale - Shift;
6792       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6793                                       Low + (V == V1 ? 0 : Size)))
6794         return SDValue();
6795     }
6796
6797     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6798     bool ByteShift = ShiftEltBits > 64;
6799     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6800                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6801     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6802
6803     // Normalize the scale for byte shifts to still produce an i64 element
6804     // type.
6805     Scale = ByteShift ? Scale / 2 : Scale;
6806
6807     // We need to round trip through the appropriate type for the shift.
6808     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6809     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6810     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6811            "Illegal integer vector type");
6812     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6813
6814     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6815                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6816     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6817   };
6818
6819   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6820   // keep doubling the size of the integer elements up to that. We can
6821   // then shift the elements of the integer vector by whole multiples of
6822   // their width within the elements of the larger integer vector. Test each
6823   // multiple to see if we can find a match with the moved element indices
6824   // and that the shifted in elements are all zeroable.
6825   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6826     for (int Shift = 1; Shift != Scale; ++Shift)
6827       for (bool Left : {true, false})
6828         if (CheckZeros(Shift, Scale, Left))
6829           for (SDValue V : {V1, V2})
6830             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6831               return Match;
6832
6833   // no match
6834   return SDValue();
6835 }
6836
6837 /// \brief Lower a vector shuffle as a zero or any extension.
6838 ///
6839 /// Given a specific number of elements, element bit width, and extension
6840 /// stride, produce either a zero or any extension based on the available
6841 /// features of the subtarget.
6842 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6843     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6844     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6845   assert(Scale > 1 && "Need a scale to extend.");
6846   int NumElements = VT.getVectorNumElements();
6847   int EltBits = VT.getScalarSizeInBits();
6848   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6849          "Only 8, 16, and 32 bit elements can be extended.");
6850   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6851
6852   // Found a valid zext mask! Try various lowering strategies based on the
6853   // input type and available ISA extensions.
6854   if (Subtarget->hasSSE41()) {
6855     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6856                                  NumElements / Scale);
6857     return DAG.getNode(ISD::BITCAST, DL, VT,
6858                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6859   }
6860
6861   // For any extends we can cheat for larger element sizes and use shuffle
6862   // instructions that can fold with a load and/or copy.
6863   if (AnyExt && EltBits == 32) {
6864     int PSHUFDMask[4] = {0, -1, 1, -1};
6865     return DAG.getNode(
6866         ISD::BITCAST, DL, VT,
6867         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6868                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6869                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6870   }
6871   if (AnyExt && EltBits == 16 && Scale > 2) {
6872     int PSHUFDMask[4] = {0, -1, 0, -1};
6873     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6874                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6875                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6876     int PSHUFHWMask[4] = {1, -1, -1, -1};
6877     return DAG.getNode(
6878         ISD::BITCAST, DL, VT,
6879         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6880                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6881                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6882   }
6883
6884   // If this would require more than 2 unpack instructions to expand, use
6885   // pshufb when available. We can only use more than 2 unpack instructions
6886   // when zero extending i8 elements which also makes it easier to use pshufb.
6887   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6888     assert(NumElements == 16 && "Unexpected byte vector width!");
6889     SDValue PSHUFBMask[16];
6890     for (int i = 0; i < 16; ++i)
6891       PSHUFBMask[i] =
6892           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6893     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6894     return DAG.getNode(ISD::BITCAST, DL, VT,
6895                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6896                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6897                                                MVT::v16i8, PSHUFBMask)));
6898   }
6899
6900   // Otherwise emit a sequence of unpacks.
6901   do {
6902     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6903     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6904                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6905     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6906     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6907     Scale /= 2;
6908     EltBits *= 2;
6909     NumElements /= 2;
6910   } while (Scale > 1);
6911   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6912 }
6913
6914 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6915 ///
6916 /// This routine will try to do everything in its power to cleverly lower
6917 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6918 /// check for the profitability of this lowering,  it tries to aggressively
6919 /// match this pattern. It will use all of the micro-architectural details it
6920 /// can to emit an efficient lowering. It handles both blends with all-zero
6921 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6922 /// masking out later).
6923 ///
6924 /// The reason we have dedicated lowering for zext-style shuffles is that they
6925 /// are both incredibly common and often quite performance sensitive.
6926 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6927     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6928     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6929   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6930
6931   int Bits = VT.getSizeInBits();
6932   int NumElements = VT.getVectorNumElements();
6933   assert(VT.getScalarSizeInBits() <= 32 &&
6934          "Exceeds 32-bit integer zero extension limit");
6935   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6936
6937   // Define a helper function to check a particular ext-scale and lower to it if
6938   // valid.
6939   auto Lower = [&](int Scale) -> SDValue {
6940     SDValue InputV;
6941     bool AnyExt = true;
6942     for (int i = 0; i < NumElements; ++i) {
6943       if (Mask[i] == -1)
6944         continue; // Valid anywhere but doesn't tell us anything.
6945       if (i % Scale != 0) {
6946         // Each of the extended elements need to be zeroable.
6947         if (!Zeroable[i])
6948           return SDValue();
6949
6950         // We no longer are in the anyext case.
6951         AnyExt = false;
6952         continue;
6953       }
6954
6955       // Each of the base elements needs to be consecutive indices into the
6956       // same input vector.
6957       SDValue V = Mask[i] < NumElements ? V1 : V2;
6958       if (!InputV)
6959         InputV = V;
6960       else if (InputV != V)
6961         return SDValue(); // Flip-flopping inputs.
6962
6963       if (Mask[i] % NumElements != i / Scale)
6964         return SDValue(); // Non-consecutive strided elements.
6965     }
6966
6967     // If we fail to find an input, we have a zero-shuffle which should always
6968     // have already been handled.
6969     // FIXME: Maybe handle this here in case during blending we end up with one?
6970     if (!InputV)
6971       return SDValue();
6972
6973     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6974         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6975   };
6976
6977   // The widest scale possible for extending is to a 64-bit integer.
6978   assert(Bits % 64 == 0 &&
6979          "The number of bits in a vector must be divisible by 64 on x86!");
6980   int NumExtElements = Bits / 64;
6981
6982   // Each iteration, try extending the elements half as much, but into twice as
6983   // many elements.
6984   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6985     assert(NumElements % NumExtElements == 0 &&
6986            "The input vector size must be divisible by the extended size.");
6987     if (SDValue V = Lower(NumElements / NumExtElements))
6988       return V;
6989   }
6990
6991   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6992   if (Bits != 128)
6993     return SDValue();
6994
6995   // Returns one of the source operands if the shuffle can be reduced to a
6996   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6997   auto CanZExtLowHalf = [&]() {
6998     for (int i = NumElements / 2; i != NumElements; ++i)
6999       if (!Zeroable[i])
7000         return SDValue();
7001     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7002       return V1;
7003     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7004       return V2;
7005     return SDValue();
7006   };
7007
7008   if (SDValue V = CanZExtLowHalf()) {
7009     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
7010     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7011     return DAG.getNode(ISD::BITCAST, DL, VT, V);
7012   }
7013
7014   // No viable ext lowering found.
7015   return SDValue();
7016 }
7017
7018 /// \brief Try to get a scalar value for a specific element of a vector.
7019 ///
7020 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7021 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7022                                               SelectionDAG &DAG) {
7023   MVT VT = V.getSimpleValueType();
7024   MVT EltVT = VT.getVectorElementType();
7025   while (V.getOpcode() == ISD::BITCAST)
7026     V = V.getOperand(0);
7027   // If the bitcasts shift the element size, we can't extract an equivalent
7028   // element from it.
7029   MVT NewVT = V.getSimpleValueType();
7030   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7031     return SDValue();
7032
7033   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7034       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7035     // Ensure the scalar operand is the same size as the destination.
7036     // FIXME: Add support for scalar truncation where possible.
7037     SDValue S = V.getOperand(Idx);
7038     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7039       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7040   }
7041
7042   return SDValue();
7043 }
7044
7045 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7046 ///
7047 /// This is particularly important because the set of instructions varies
7048 /// significantly based on whether the operand is a load or not.
7049 static bool isShuffleFoldableLoad(SDValue V) {
7050   while (V.getOpcode() == ISD::BITCAST)
7051     V = V.getOperand(0);
7052
7053   return ISD::isNON_EXTLoad(V.getNode());
7054 }
7055
7056 /// \brief Try to lower insertion of a single element into a zero vector.
7057 ///
7058 /// This is a common pattern that we have especially efficient patterns to lower
7059 /// across all subtarget feature sets.
7060 static SDValue lowerVectorShuffleAsElementInsertion(
7061     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7062     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7063   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7064   MVT ExtVT = VT;
7065   MVT EltVT = VT.getVectorElementType();
7066
7067   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7068                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7069                 Mask.begin();
7070   bool IsV1Zeroable = true;
7071   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7072     if (i != V2Index && !Zeroable[i]) {
7073       IsV1Zeroable = false;
7074       break;
7075     }
7076
7077   // Check for a single input from a SCALAR_TO_VECTOR node.
7078   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7079   // all the smarts here sunk into that routine. However, the current
7080   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7081   // vector shuffle lowering is dead.
7082   if (SDValue V2S = getScalarValueForVectorElement(
7083           V2, Mask[V2Index] - Mask.size(), DAG)) {
7084     // We need to zext the scalar if it is smaller than an i32.
7085     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7086     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7087       // Using zext to expand a narrow element won't work for non-zero
7088       // insertions.
7089       if (!IsV1Zeroable)
7090         return SDValue();
7091
7092       // Zero-extend directly to i32.
7093       ExtVT = MVT::v4i32;
7094       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7095     }
7096     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7097   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7098              EltVT == MVT::i16) {
7099     // Either not inserting from the low element of the input or the input
7100     // element size is too small to use VZEXT_MOVL to clear the high bits.
7101     return SDValue();
7102   }
7103
7104   if (!IsV1Zeroable) {
7105     // If V1 can't be treated as a zero vector we have fewer options to lower
7106     // this. We can't support integer vectors or non-zero targets cheaply, and
7107     // the V1 elements can't be permuted in any way.
7108     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7109     if (!VT.isFloatingPoint() || V2Index != 0)
7110       return SDValue();
7111     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7112     V1Mask[V2Index] = -1;
7113     if (!isNoopShuffleMask(V1Mask))
7114       return SDValue();
7115     // This is essentially a special case blend operation, but if we have
7116     // general purpose blend operations, they are always faster. Bail and let
7117     // the rest of the lowering handle these as blends.
7118     if (Subtarget->hasSSE41())
7119       return SDValue();
7120
7121     // Otherwise, use MOVSD or MOVSS.
7122     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7123            "Only two types of floating point element types to handle!");
7124     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7125                        ExtVT, V1, V2);
7126   }
7127
7128   // This lowering only works for the low element with floating point vectors.
7129   if (VT.isFloatingPoint() && V2Index != 0)
7130     return SDValue();
7131
7132   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7133   if (ExtVT != VT)
7134     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7135
7136   if (V2Index != 0) {
7137     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7138     // the desired position. Otherwise it is more efficient to do a vector
7139     // shift left. We know that we can do a vector shift left because all
7140     // the inputs are zero.
7141     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7142       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7143       V2Shuffle[V2Index] = 0;
7144       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7145     } else {
7146       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7147       V2 = DAG.getNode(
7148           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7149           DAG.getConstant(
7150               V2Index * EltVT.getSizeInBits()/8, DL,
7151               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7152       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7153     }
7154   }
7155   return V2;
7156 }
7157
7158 /// \brief Try to lower broadcast of a single element.
7159 ///
7160 /// For convenience, this code also bundles all of the subtarget feature set
7161 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7162 /// a convenient way to factor it out.
7163 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7164                                              ArrayRef<int> Mask,
7165                                              const X86Subtarget *Subtarget,
7166                                              SelectionDAG &DAG) {
7167   if (!Subtarget->hasAVX())
7168     return SDValue();
7169   if (VT.isInteger() && !Subtarget->hasAVX2())
7170     return SDValue();
7171
7172   // Check that the mask is a broadcast.
7173   int BroadcastIdx = -1;
7174   for (int M : Mask)
7175     if (M >= 0 && BroadcastIdx == -1)
7176       BroadcastIdx = M;
7177     else if (M >= 0 && M != BroadcastIdx)
7178       return SDValue();
7179
7180   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7181                                             "a sorted mask where the broadcast "
7182                                             "comes from V1.");
7183
7184   // Go up the chain of (vector) values to find a scalar load that we can
7185   // combine with the broadcast.
7186   for (;;) {
7187     switch (V.getOpcode()) {
7188     case ISD::CONCAT_VECTORS: {
7189       int OperandSize = Mask.size() / V.getNumOperands();
7190       V = V.getOperand(BroadcastIdx / OperandSize);
7191       BroadcastIdx %= OperandSize;
7192       continue;
7193     }
7194
7195     case ISD::INSERT_SUBVECTOR: {
7196       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7197       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7198       if (!ConstantIdx)
7199         break;
7200
7201       int BeginIdx = (int)ConstantIdx->getZExtValue();
7202       int EndIdx =
7203           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7204       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7205         BroadcastIdx -= BeginIdx;
7206         V = VInner;
7207       } else {
7208         V = VOuter;
7209       }
7210       continue;
7211     }
7212     }
7213     break;
7214   }
7215
7216   // Check if this is a broadcast of a scalar. We special case lowering
7217   // for scalars so that we can more effectively fold with loads.
7218   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7219       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7220     V = V.getOperand(BroadcastIdx);
7221
7222     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7223     // Only AVX2 has register broadcasts.
7224     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7225       return SDValue();
7226   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7227     // We can't broadcast from a vector register without AVX2, and we can only
7228     // broadcast from the zero-element of a vector register.
7229     return SDValue();
7230   }
7231
7232   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7233 }
7234
7235 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7236 // INSERTPS when the V1 elements are already in the correct locations
7237 // because otherwise we can just always use two SHUFPS instructions which
7238 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7239 // perform INSERTPS if a single V1 element is out of place and all V2
7240 // elements are zeroable.
7241 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7242                                             ArrayRef<int> Mask,
7243                                             SelectionDAG &DAG) {
7244   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7245   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7246   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7247   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7248
7249   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7250
7251   unsigned ZMask = 0;
7252   int V1DstIndex = -1;
7253   int V2DstIndex = -1;
7254   bool V1UsedInPlace = false;
7255
7256   for (int i = 0; i < 4; ++i) {
7257     // Synthesize a zero mask from the zeroable elements (includes undefs).
7258     if (Zeroable[i]) {
7259       ZMask |= 1 << i;
7260       continue;
7261     }
7262
7263     // Flag if we use any V1 inputs in place.
7264     if (i == Mask[i]) {
7265       V1UsedInPlace = true;
7266       continue;
7267     }
7268
7269     // We can only insert a single non-zeroable element.
7270     if (V1DstIndex != -1 || V2DstIndex != -1)
7271       return SDValue();
7272
7273     if (Mask[i] < 4) {
7274       // V1 input out of place for insertion.
7275       V1DstIndex = i;
7276     } else {
7277       // V2 input for insertion.
7278       V2DstIndex = i;
7279     }
7280   }
7281
7282   // Don't bother if we have no (non-zeroable) element for insertion.
7283   if (V1DstIndex == -1 && V2DstIndex == -1)
7284     return SDValue();
7285
7286   // Determine element insertion src/dst indices. The src index is from the
7287   // start of the inserted vector, not the start of the concatenated vector.
7288   unsigned V2SrcIndex = 0;
7289   if (V1DstIndex != -1) {
7290     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7291     // and don't use the original V2 at all.
7292     V2SrcIndex = Mask[V1DstIndex];
7293     V2DstIndex = V1DstIndex;
7294     V2 = V1;
7295   } else {
7296     V2SrcIndex = Mask[V2DstIndex] - 4;
7297   }
7298
7299   // If no V1 inputs are used in place, then the result is created only from
7300   // the zero mask and the V2 insertion - so remove V1 dependency.
7301   if (!V1UsedInPlace)
7302     V1 = DAG.getUNDEF(MVT::v4f32);
7303
7304   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7305   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7306
7307   // Insert the V2 element into the desired position.
7308   SDLoc DL(Op);
7309   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7310                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7311 }
7312
7313 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7314 /// UNPCK instruction.
7315 ///
7316 /// This specifically targets cases where we end up with alternating between
7317 /// the two inputs, and so can permute them into something that feeds a single
7318 /// UNPCK instruction. Note that this routine only targets integer vectors
7319 /// because for floating point vectors we have a generalized SHUFPS lowering
7320 /// strategy that handles everything that doesn't *exactly* match an unpack,
7321 /// making this clever lowering unnecessary.
7322 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7323                                           SDValue V2, ArrayRef<int> Mask,
7324                                           SelectionDAG &DAG) {
7325   assert(!VT.isFloatingPoint() &&
7326          "This routine only supports integer vectors.");
7327   assert(!isSingleInputShuffleMask(Mask) &&
7328          "This routine should only be used when blending two inputs.");
7329   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7330
7331   int Size = Mask.size();
7332
7333   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7334     return M >= 0 && M % Size < Size / 2;
7335   });
7336   int NumHiInputs = std::count_if(
7337       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7338
7339   bool UnpackLo = NumLoInputs >= NumHiInputs;
7340
7341   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7342     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7343     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7344
7345     for (int i = 0; i < Size; ++i) {
7346       if (Mask[i] < 0)
7347         continue;
7348
7349       // Each element of the unpack contains Scale elements from this mask.
7350       int UnpackIdx = i / Scale;
7351
7352       // We only handle the case where V1 feeds the first slots of the unpack.
7353       // We rely on canonicalization to ensure this is the case.
7354       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7355         return SDValue();
7356
7357       // Setup the mask for this input. The indexing is tricky as we have to
7358       // handle the unpack stride.
7359       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7360       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7361           Mask[i] % Size;
7362     }
7363
7364     // If we will have to shuffle both inputs to use the unpack, check whether
7365     // we can just unpack first and shuffle the result. If so, skip this unpack.
7366     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7367         !isNoopShuffleMask(V2Mask))
7368       return SDValue();
7369
7370     // Shuffle the inputs into place.
7371     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7372     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7373
7374     // Cast the inputs to the type we will use to unpack them.
7375     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7376     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7377
7378     // Unpack the inputs and cast the result back to the desired type.
7379     return DAG.getNode(ISD::BITCAST, DL, VT,
7380                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7381                                    DL, UnpackVT, V1, V2));
7382   };
7383
7384   // We try each unpack from the largest to the smallest to try and find one
7385   // that fits this mask.
7386   int OrigNumElements = VT.getVectorNumElements();
7387   int OrigScalarSize = VT.getScalarSizeInBits();
7388   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7389     int Scale = ScalarSize / OrigScalarSize;
7390     int NumElements = OrigNumElements / Scale;
7391     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7392     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7393       return Unpack;
7394   }
7395
7396   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7397   // initial unpack.
7398   if (NumLoInputs == 0 || NumHiInputs == 0) {
7399     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7400            "We have to have *some* inputs!");
7401     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7402
7403     // FIXME: We could consider the total complexity of the permute of each
7404     // possible unpacking. Or at the least we should consider how many
7405     // half-crossings are created.
7406     // FIXME: We could consider commuting the unpacks.
7407
7408     SmallVector<int, 32> PermMask;
7409     PermMask.assign(Size, -1);
7410     for (int i = 0; i < Size; ++i) {
7411       if (Mask[i] < 0)
7412         continue;
7413
7414       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7415
7416       PermMask[i] =
7417           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7418     }
7419     return DAG.getVectorShuffle(
7420         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7421                             DL, VT, V1, V2),
7422         DAG.getUNDEF(VT), PermMask);
7423   }
7424
7425   return SDValue();
7426 }
7427
7428 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7429 ///
7430 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7431 /// support for floating point shuffles but not integer shuffles. These
7432 /// instructions will incur a domain crossing penalty on some chips though so
7433 /// it is better to avoid lowering through this for integer vectors where
7434 /// possible.
7435 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7436                                        const X86Subtarget *Subtarget,
7437                                        SelectionDAG &DAG) {
7438   SDLoc DL(Op);
7439   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7440   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7441   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7442   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7443   ArrayRef<int> Mask = SVOp->getMask();
7444   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7445
7446   if (isSingleInputShuffleMask(Mask)) {
7447     // Use low duplicate instructions for masks that match their pattern.
7448     if (Subtarget->hasSSE3())
7449       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7450         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7451
7452     // Straight shuffle of a single input vector. Simulate this by using the
7453     // single input as both of the "inputs" to this instruction..
7454     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7455
7456     if (Subtarget->hasAVX()) {
7457       // If we have AVX, we can use VPERMILPS which will allow folding a load
7458       // into the shuffle.
7459       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7460                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7461     }
7462
7463     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7464                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7465   }
7466   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7467   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7468
7469   // If we have a single input, insert that into V1 if we can do so cheaply.
7470   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7471     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7472             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7473       return Insertion;
7474     // Try inverting the insertion since for v2 masks it is easy to do and we
7475     // can't reliably sort the mask one way or the other.
7476     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7477                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7478     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7479             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7480       return Insertion;
7481   }
7482
7483   // Try to use one of the special instruction patterns to handle two common
7484   // blend patterns if a zero-blend above didn't work.
7485   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7486       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7487     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7488       // We can either use a special instruction to load over the low double or
7489       // to move just the low double.
7490       return DAG.getNode(
7491           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7492           DL, MVT::v2f64, V2,
7493           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7494
7495   if (Subtarget->hasSSE41())
7496     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7497                                                   Subtarget, DAG))
7498       return Blend;
7499
7500   // Use dedicated unpack instructions for masks that match their pattern.
7501   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7502     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7503   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7504     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7505
7506   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7507   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7508                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7509 }
7510
7511 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7512 ///
7513 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7514 /// the integer unit to minimize domain crossing penalties. However, for blends
7515 /// it falls back to the floating point shuffle operation with appropriate bit
7516 /// casting.
7517 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7518                                        const X86Subtarget *Subtarget,
7519                                        SelectionDAG &DAG) {
7520   SDLoc DL(Op);
7521   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7522   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7523   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7524   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7525   ArrayRef<int> Mask = SVOp->getMask();
7526   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7527
7528   if (isSingleInputShuffleMask(Mask)) {
7529     // Check for being able to broadcast a single element.
7530     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7531                                                           Mask, Subtarget, DAG))
7532       return Broadcast;
7533
7534     // Straight shuffle of a single input vector. For everything from SSE2
7535     // onward this has a single fast instruction with no scary immediates.
7536     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7537     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7538     int WidenedMask[4] = {
7539         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7540         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7541     return DAG.getNode(
7542         ISD::BITCAST, DL, MVT::v2i64,
7543         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7544                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7545   }
7546   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7547   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7548   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7549   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7550
7551   // If we have a blend of two PACKUS operations an the blend aligns with the
7552   // low and half halves, we can just merge the PACKUS operations. This is
7553   // particularly important as it lets us merge shuffles that this routine itself
7554   // creates.
7555   auto GetPackNode = [](SDValue V) {
7556     while (V.getOpcode() == ISD::BITCAST)
7557       V = V.getOperand(0);
7558
7559     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7560   };
7561   if (SDValue V1Pack = GetPackNode(V1))
7562     if (SDValue V2Pack = GetPackNode(V2))
7563       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7564                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7565                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7566                                                   : V1Pack.getOperand(1),
7567                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7568                                                   : V2Pack.getOperand(1)));
7569
7570   // Try to use shift instructions.
7571   if (SDValue Shift =
7572           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7573     return Shift;
7574
7575   // When loading a scalar and then shuffling it into a vector we can often do
7576   // the insertion cheaply.
7577   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7578           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7579     return Insertion;
7580   // Try inverting the insertion since for v2 masks it is easy to do and we
7581   // can't reliably sort the mask one way or the other.
7582   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7583   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7584           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7585     return Insertion;
7586
7587   // We have different paths for blend lowering, but they all must use the
7588   // *exact* same predicate.
7589   bool IsBlendSupported = Subtarget->hasSSE41();
7590   if (IsBlendSupported)
7591     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7592                                                   Subtarget, DAG))
7593       return Blend;
7594
7595   // Use dedicated unpack instructions for masks that match their pattern.
7596   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7597     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7598   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7599     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7600
7601   // Try to use byte rotation instructions.
7602   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7603   if (Subtarget->hasSSSE3())
7604     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7605             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7606       return Rotate;
7607
7608   // If we have direct support for blends, we should lower by decomposing into
7609   // a permute. That will be faster than the domain cross.
7610   if (IsBlendSupported)
7611     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7612                                                       Mask, DAG);
7613
7614   // We implement this with SHUFPD which is pretty lame because it will likely
7615   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7616   // However, all the alternatives are still more cycles and newer chips don't
7617   // have this problem. It would be really nice if x86 had better shuffles here.
7618   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7619   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7620   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7621                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7622 }
7623
7624 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7625 ///
7626 /// This is used to disable more specialized lowerings when the shufps lowering
7627 /// will happen to be efficient.
7628 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7629   // This routine only handles 128-bit shufps.
7630   assert(Mask.size() == 4 && "Unsupported mask size!");
7631
7632   // To lower with a single SHUFPS we need to have the low half and high half
7633   // each requiring a single input.
7634   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7635     return false;
7636   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7637     return false;
7638
7639   return true;
7640 }
7641
7642 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7643 ///
7644 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7645 /// It makes no assumptions about whether this is the *best* lowering, it simply
7646 /// uses it.
7647 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7648                                             ArrayRef<int> Mask, SDValue V1,
7649                                             SDValue V2, SelectionDAG &DAG) {
7650   SDValue LowV = V1, HighV = V2;
7651   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7652
7653   int NumV2Elements =
7654       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7655
7656   if (NumV2Elements == 1) {
7657     int V2Index =
7658         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7659         Mask.begin();
7660
7661     // Compute the index adjacent to V2Index and in the same half by toggling
7662     // the low bit.
7663     int V2AdjIndex = V2Index ^ 1;
7664
7665     if (Mask[V2AdjIndex] == -1) {
7666       // Handles all the cases where we have a single V2 element and an undef.
7667       // This will only ever happen in the high lanes because we commute the
7668       // vector otherwise.
7669       if (V2Index < 2)
7670         std::swap(LowV, HighV);
7671       NewMask[V2Index] -= 4;
7672     } else {
7673       // Handle the case where the V2 element ends up adjacent to a V1 element.
7674       // To make this work, blend them together as the first step.
7675       int V1Index = V2AdjIndex;
7676       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7677       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7678                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7679
7680       // Now proceed to reconstruct the final blend as we have the necessary
7681       // high or low half formed.
7682       if (V2Index < 2) {
7683         LowV = V2;
7684         HighV = V1;
7685       } else {
7686         HighV = V2;
7687       }
7688       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7689       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7690     }
7691   } else if (NumV2Elements == 2) {
7692     if (Mask[0] < 4 && Mask[1] < 4) {
7693       // Handle the easy case where we have V1 in the low lanes and V2 in the
7694       // high lanes.
7695       NewMask[2] -= 4;
7696       NewMask[3] -= 4;
7697     } else if (Mask[2] < 4 && Mask[3] < 4) {
7698       // We also handle the reversed case because this utility may get called
7699       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7700       // arrange things in the right direction.
7701       NewMask[0] -= 4;
7702       NewMask[1] -= 4;
7703       HighV = V1;
7704       LowV = V2;
7705     } else {
7706       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7707       // trying to place elements directly, just blend them and set up the final
7708       // shuffle to place them.
7709
7710       // The first two blend mask elements are for V1, the second two are for
7711       // V2.
7712       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7713                           Mask[2] < 4 ? Mask[2] : Mask[3],
7714                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7715                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7716       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7717                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7718
7719       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7720       // a blend.
7721       LowV = HighV = V1;
7722       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7723       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7724       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7725       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7726     }
7727   }
7728   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7729                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7730 }
7731
7732 /// \brief Lower 4-lane 32-bit floating point shuffles.
7733 ///
7734 /// Uses instructions exclusively from the floating point unit to minimize
7735 /// domain crossing penalties, as these are sufficient to implement all v4f32
7736 /// shuffles.
7737 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7738                                        const X86Subtarget *Subtarget,
7739                                        SelectionDAG &DAG) {
7740   SDLoc DL(Op);
7741   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7742   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7743   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7744   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7745   ArrayRef<int> Mask = SVOp->getMask();
7746   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7747
7748   int NumV2Elements =
7749       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7750
7751   if (NumV2Elements == 0) {
7752     // Check for being able to broadcast a single element.
7753     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7754                                                           Mask, Subtarget, DAG))
7755       return Broadcast;
7756
7757     // Use even/odd duplicate instructions for masks that match their pattern.
7758     if (Subtarget->hasSSE3()) {
7759       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7760         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7761       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7762         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7763     }
7764
7765     if (Subtarget->hasAVX()) {
7766       // If we have AVX, we can use VPERMILPS which will allow folding a load
7767       // into the shuffle.
7768       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7769                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7770     }
7771
7772     // Otherwise, use a straight shuffle of a single input vector. We pass the
7773     // input vector to both operands to simulate this with a SHUFPS.
7774     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7775                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7776   }
7777
7778   // There are special ways we can lower some single-element blends. However, we
7779   // have custom ways we can lower more complex single-element blends below that
7780   // we defer to if both this and BLENDPS fail to match, so restrict this to
7781   // when the V2 input is targeting element 0 of the mask -- that is the fast
7782   // case here.
7783   if (NumV2Elements == 1 && Mask[0] >= 4)
7784     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7785                                                          Mask, Subtarget, DAG))
7786       return V;
7787
7788   if (Subtarget->hasSSE41()) {
7789     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7790                                                   Subtarget, DAG))
7791       return Blend;
7792
7793     // Use INSERTPS if we can complete the shuffle efficiently.
7794     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7795       return V;
7796
7797     if (!isSingleSHUFPSMask(Mask))
7798       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7799               DL, MVT::v4f32, V1, V2, Mask, DAG))
7800         return BlendPerm;
7801   }
7802
7803   // Use dedicated unpack instructions for masks that match their pattern.
7804   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7805     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7806   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7807     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7808   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7809     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7810   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7811     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7812
7813   // Otherwise fall back to a SHUFPS lowering strategy.
7814   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7815 }
7816
7817 /// \brief Lower 4-lane i32 vector shuffles.
7818 ///
7819 /// We try to handle these with integer-domain shuffles where we can, but for
7820 /// blends we use the floating point domain blend instructions.
7821 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7822                                        const X86Subtarget *Subtarget,
7823                                        SelectionDAG &DAG) {
7824   SDLoc DL(Op);
7825   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7826   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7827   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7828   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7829   ArrayRef<int> Mask = SVOp->getMask();
7830   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7831
7832   // Whenever we can lower this as a zext, that instruction is strictly faster
7833   // than any alternative. It also allows us to fold memory operands into the
7834   // shuffle in many cases.
7835   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7836                                                          Mask, Subtarget, DAG))
7837     return ZExt;
7838
7839   int NumV2Elements =
7840       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7841
7842   if (NumV2Elements == 0) {
7843     // Check for being able to broadcast a single element.
7844     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7845                                                           Mask, Subtarget, DAG))
7846       return Broadcast;
7847
7848     // Straight shuffle of a single input vector. For everything from SSE2
7849     // onward this has a single fast instruction with no scary immediates.
7850     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7851     // but we aren't actually going to use the UNPCK instruction because doing
7852     // so prevents folding a load into this instruction or making a copy.
7853     const int UnpackLoMask[] = {0, 0, 1, 1};
7854     const int UnpackHiMask[] = {2, 2, 3, 3};
7855     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7856       Mask = UnpackLoMask;
7857     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7858       Mask = UnpackHiMask;
7859
7860     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7861                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7862   }
7863
7864   // Try to use shift instructions.
7865   if (SDValue Shift =
7866           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7867     return Shift;
7868
7869   // There are special ways we can lower some single-element blends.
7870   if (NumV2Elements == 1)
7871     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7872                                                          Mask, Subtarget, DAG))
7873       return V;
7874
7875   // We have different paths for blend lowering, but they all must use the
7876   // *exact* same predicate.
7877   bool IsBlendSupported = Subtarget->hasSSE41();
7878   if (IsBlendSupported)
7879     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7880                                                   Subtarget, DAG))
7881       return Blend;
7882
7883   if (SDValue Masked =
7884           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7885     return Masked;
7886
7887   // Use dedicated unpack instructions for masks that match their pattern.
7888   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7889     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7890   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7891     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7892   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7893     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7894   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7895     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7896
7897   // Try to use byte rotation instructions.
7898   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7899   if (Subtarget->hasSSSE3())
7900     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7901             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7902       return Rotate;
7903
7904   // If we have direct support for blends, we should lower by decomposing into
7905   // a permute. That will be faster than the domain cross.
7906   if (IsBlendSupported)
7907     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7908                                                       Mask, DAG);
7909
7910   // Try to lower by permuting the inputs into an unpack instruction.
7911   if (SDValue Unpack =
7912           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7913     return Unpack;
7914
7915   // We implement this with SHUFPS because it can blend from two vectors.
7916   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7917   // up the inputs, bypassing domain shift penalties that we would encur if we
7918   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7919   // relevant.
7920   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7921                      DAG.getVectorShuffle(
7922                          MVT::v4f32, DL,
7923                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7924                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7925 }
7926
7927 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7928 /// shuffle lowering, and the most complex part.
7929 ///
7930 /// The lowering strategy is to try to form pairs of input lanes which are
7931 /// targeted at the same half of the final vector, and then use a dword shuffle
7932 /// to place them onto the right half, and finally unpack the paired lanes into
7933 /// their final position.
7934 ///
7935 /// The exact breakdown of how to form these dword pairs and align them on the
7936 /// correct sides is really tricky. See the comments within the function for
7937 /// more of the details.
7938 ///
7939 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7940 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7941 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7942 /// vector, form the analogous 128-bit 8-element Mask.
7943 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7944     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7945     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7946   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7947   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7948
7949   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7950   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7951   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7952
7953   SmallVector<int, 4> LoInputs;
7954   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7955                [](int M) { return M >= 0; });
7956   std::sort(LoInputs.begin(), LoInputs.end());
7957   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7958   SmallVector<int, 4> HiInputs;
7959   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7960                [](int M) { return M >= 0; });
7961   std::sort(HiInputs.begin(), HiInputs.end());
7962   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7963   int NumLToL =
7964       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7965   int NumHToL = LoInputs.size() - NumLToL;
7966   int NumLToH =
7967       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7968   int NumHToH = HiInputs.size() - NumLToH;
7969   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7970   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7971   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7972   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7973
7974   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7975   // such inputs we can swap two of the dwords across the half mark and end up
7976   // with <=2 inputs to each half in each half. Once there, we can fall through
7977   // to the generic code below. For example:
7978   //
7979   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7980   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7981   //
7982   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7983   // and an existing 2-into-2 on the other half. In this case we may have to
7984   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7985   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7986   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7987   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7988   // half than the one we target for fixing) will be fixed when we re-enter this
7989   // path. We will also combine away any sequence of PSHUFD instructions that
7990   // result into a single instruction. Here is an example of the tricky case:
7991   //
7992   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7993   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7994   //
7995   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7996   //
7997   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7998   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7999   //
8000   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8001   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8002   //
8003   // The result is fine to be handled by the generic logic.
8004   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8005                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8006                           int AOffset, int BOffset) {
8007     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8008            "Must call this with A having 3 or 1 inputs from the A half.");
8009     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8010            "Must call this with B having 1 or 3 inputs from the B half.");
8011     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8012            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8013
8014     // Compute the index of dword with only one word among the three inputs in
8015     // a half by taking the sum of the half with three inputs and subtracting
8016     // the sum of the actual three inputs. The difference is the remaining
8017     // slot.
8018     int ADWord, BDWord;
8019     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8020     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8021     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8022     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8023     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8024     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8025     int TripleNonInputIdx =
8026         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8027     TripleDWord = TripleNonInputIdx / 2;
8028
8029     // We use xor with one to compute the adjacent DWord to whichever one the
8030     // OneInput is in.
8031     OneInputDWord = (OneInput / 2) ^ 1;
8032
8033     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8034     // and BToA inputs. If there is also such a problem with the BToB and AToB
8035     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8036     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8037     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8038     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8039       // Compute how many inputs will be flipped by swapping these DWords. We
8040       // need
8041       // to balance this to ensure we don't form a 3-1 shuffle in the other
8042       // half.
8043       int NumFlippedAToBInputs =
8044           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8045           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8046       int NumFlippedBToBInputs =
8047           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8048           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8049       if ((NumFlippedAToBInputs == 1 &&
8050            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8051           (NumFlippedBToBInputs == 1 &&
8052            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8053         // We choose whether to fix the A half or B half based on whether that
8054         // half has zero flipped inputs. At zero, we may not be able to fix it
8055         // with that half. We also bias towards fixing the B half because that
8056         // will more commonly be the high half, and we have to bias one way.
8057         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8058                                                        ArrayRef<int> Inputs) {
8059           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8060           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8061                                          PinnedIdx ^ 1) != Inputs.end();
8062           // Determine whether the free index is in the flipped dword or the
8063           // unflipped dword based on where the pinned index is. We use this bit
8064           // in an xor to conditionally select the adjacent dword.
8065           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8066           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8067                                              FixFreeIdx) != Inputs.end();
8068           if (IsFixIdxInput == IsFixFreeIdxInput)
8069             FixFreeIdx += 1;
8070           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8071                                         FixFreeIdx) != Inputs.end();
8072           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8073                  "We need to be changing the number of flipped inputs!");
8074           int PSHUFHalfMask[] = {0, 1, 2, 3};
8075           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8076           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8077                           MVT::v8i16, V,
8078                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8079
8080           for (int &M : Mask)
8081             if (M != -1 && M == FixIdx)
8082               M = FixFreeIdx;
8083             else if (M != -1 && M == FixFreeIdx)
8084               M = FixIdx;
8085         };
8086         if (NumFlippedBToBInputs != 0) {
8087           int BPinnedIdx =
8088               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8089           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8090         } else {
8091           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8092           int APinnedIdx =
8093               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8094           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8095         }
8096       }
8097     }
8098
8099     int PSHUFDMask[] = {0, 1, 2, 3};
8100     PSHUFDMask[ADWord] = BDWord;
8101     PSHUFDMask[BDWord] = ADWord;
8102     V = DAG.getNode(ISD::BITCAST, DL, VT,
8103                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8104                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8105                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8106                                                            DAG)));
8107
8108     // Adjust the mask to match the new locations of A and B.
8109     for (int &M : Mask)
8110       if (M != -1 && M/2 == ADWord)
8111         M = 2 * BDWord + M % 2;
8112       else if (M != -1 && M/2 == BDWord)
8113         M = 2 * ADWord + M % 2;
8114
8115     // Recurse back into this routine to re-compute state now that this isn't
8116     // a 3 and 1 problem.
8117     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8118                                                      DAG);
8119   };
8120   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8121     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8122   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8123     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8124
8125   // At this point there are at most two inputs to the low and high halves from
8126   // each half. That means the inputs can always be grouped into dwords and
8127   // those dwords can then be moved to the correct half with a dword shuffle.
8128   // We use at most one low and one high word shuffle to collect these paired
8129   // inputs into dwords, and finally a dword shuffle to place them.
8130   int PSHUFLMask[4] = {-1, -1, -1, -1};
8131   int PSHUFHMask[4] = {-1, -1, -1, -1};
8132   int PSHUFDMask[4] = {-1, -1, -1, -1};
8133
8134   // First fix the masks for all the inputs that are staying in their
8135   // original halves. This will then dictate the targets of the cross-half
8136   // shuffles.
8137   auto fixInPlaceInputs =
8138       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8139                     MutableArrayRef<int> SourceHalfMask,
8140                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8141     if (InPlaceInputs.empty())
8142       return;
8143     if (InPlaceInputs.size() == 1) {
8144       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8145           InPlaceInputs[0] - HalfOffset;
8146       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8147       return;
8148     }
8149     if (IncomingInputs.empty()) {
8150       // Just fix all of the in place inputs.
8151       for (int Input : InPlaceInputs) {
8152         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8153         PSHUFDMask[Input / 2] = Input / 2;
8154       }
8155       return;
8156     }
8157
8158     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8159     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8160         InPlaceInputs[0] - HalfOffset;
8161     // Put the second input next to the first so that they are packed into
8162     // a dword. We find the adjacent index by toggling the low bit.
8163     int AdjIndex = InPlaceInputs[0] ^ 1;
8164     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8165     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8166     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8167   };
8168   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8169   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8170
8171   // Now gather the cross-half inputs and place them into a free dword of
8172   // their target half.
8173   // FIXME: This operation could almost certainly be simplified dramatically to
8174   // look more like the 3-1 fixing operation.
8175   auto moveInputsToRightHalf = [&PSHUFDMask](
8176       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8177       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8178       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8179       int DestOffset) {
8180     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8181       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8182     };
8183     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8184                                                int Word) {
8185       int LowWord = Word & ~1;
8186       int HighWord = Word | 1;
8187       return isWordClobbered(SourceHalfMask, LowWord) ||
8188              isWordClobbered(SourceHalfMask, HighWord);
8189     };
8190
8191     if (IncomingInputs.empty())
8192       return;
8193
8194     if (ExistingInputs.empty()) {
8195       // Map any dwords with inputs from them into the right half.
8196       for (int Input : IncomingInputs) {
8197         // If the source half mask maps over the inputs, turn those into
8198         // swaps and use the swapped lane.
8199         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8200           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8201             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8202                 Input - SourceOffset;
8203             // We have to swap the uses in our half mask in one sweep.
8204             for (int &M : HalfMask)
8205               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8206                 M = Input;
8207               else if (M == Input)
8208                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8209           } else {
8210             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8211                        Input - SourceOffset &&
8212                    "Previous placement doesn't match!");
8213           }
8214           // Note that this correctly re-maps both when we do a swap and when
8215           // we observe the other side of the swap above. We rely on that to
8216           // avoid swapping the members of the input list directly.
8217           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8218         }
8219
8220         // Map the input's dword into the correct half.
8221         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8222           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8223         else
8224           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8225                      Input / 2 &&
8226                  "Previous placement doesn't match!");
8227       }
8228
8229       // And just directly shift any other-half mask elements to be same-half
8230       // as we will have mirrored the dword containing the element into the
8231       // same position within that half.
8232       for (int &M : HalfMask)
8233         if (M >= SourceOffset && M < SourceOffset + 4) {
8234           M = M - SourceOffset + DestOffset;
8235           assert(M >= 0 && "This should never wrap below zero!");
8236         }
8237       return;
8238     }
8239
8240     // Ensure we have the input in a viable dword of its current half. This
8241     // is particularly tricky because the original position may be clobbered
8242     // by inputs being moved and *staying* in that half.
8243     if (IncomingInputs.size() == 1) {
8244       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8245         int InputFixed = std::find(std::begin(SourceHalfMask),
8246                                    std::end(SourceHalfMask), -1) -
8247                          std::begin(SourceHalfMask) + SourceOffset;
8248         SourceHalfMask[InputFixed - SourceOffset] =
8249             IncomingInputs[0] - SourceOffset;
8250         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8251                      InputFixed);
8252         IncomingInputs[0] = InputFixed;
8253       }
8254     } else if (IncomingInputs.size() == 2) {
8255       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8256           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8257         // We have two non-adjacent or clobbered inputs we need to extract from
8258         // the source half. To do this, we need to map them into some adjacent
8259         // dword slot in the source mask.
8260         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8261                               IncomingInputs[1] - SourceOffset};
8262
8263         // If there is a free slot in the source half mask adjacent to one of
8264         // the inputs, place the other input in it. We use (Index XOR 1) to
8265         // compute an adjacent index.
8266         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8267             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8268           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8269           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8270           InputsFixed[1] = InputsFixed[0] ^ 1;
8271         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8272                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8273           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8274           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8275           InputsFixed[0] = InputsFixed[1] ^ 1;
8276         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8277                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8278           // The two inputs are in the same DWord but it is clobbered and the
8279           // adjacent DWord isn't used at all. Move both inputs to the free
8280           // slot.
8281           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8282           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8283           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8284           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8285         } else {
8286           // The only way we hit this point is if there is no clobbering
8287           // (because there are no off-half inputs to this half) and there is no
8288           // free slot adjacent to one of the inputs. In this case, we have to
8289           // swap an input with a non-input.
8290           for (int i = 0; i < 4; ++i)
8291             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8292                    "We can't handle any clobbers here!");
8293           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8294                  "Cannot have adjacent inputs here!");
8295
8296           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8297           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8298
8299           // We also have to update the final source mask in this case because
8300           // it may need to undo the above swap.
8301           for (int &M : FinalSourceHalfMask)
8302             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8303               M = InputsFixed[1] + SourceOffset;
8304             else if (M == InputsFixed[1] + SourceOffset)
8305               M = (InputsFixed[0] ^ 1) + SourceOffset;
8306
8307           InputsFixed[1] = InputsFixed[0] ^ 1;
8308         }
8309
8310         // Point everything at the fixed inputs.
8311         for (int &M : HalfMask)
8312           if (M == IncomingInputs[0])
8313             M = InputsFixed[0] + SourceOffset;
8314           else if (M == IncomingInputs[1])
8315             M = InputsFixed[1] + SourceOffset;
8316
8317         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8318         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8319       }
8320     } else {
8321       llvm_unreachable("Unhandled input size!");
8322     }
8323
8324     // Now hoist the DWord down to the right half.
8325     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8326     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8327     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8328     for (int &M : HalfMask)
8329       for (int Input : IncomingInputs)
8330         if (M == Input)
8331           M = FreeDWord * 2 + Input % 2;
8332   };
8333   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8334                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8335   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8336                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8337
8338   // Now enact all the shuffles we've computed to move the inputs into their
8339   // target half.
8340   if (!isNoopShuffleMask(PSHUFLMask))
8341     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8342                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8343   if (!isNoopShuffleMask(PSHUFHMask))
8344     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8345                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8346   if (!isNoopShuffleMask(PSHUFDMask))
8347     V = DAG.getNode(ISD::BITCAST, DL, VT,
8348                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8349                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8350                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8351                                                            DAG)));
8352
8353   // At this point, each half should contain all its inputs, and we can then
8354   // just shuffle them into their final position.
8355   assert(std::count_if(LoMask.begin(), LoMask.end(),
8356                        [](int M) { return M >= 4; }) == 0 &&
8357          "Failed to lift all the high half inputs to the low mask!");
8358   assert(std::count_if(HiMask.begin(), HiMask.end(),
8359                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8360          "Failed to lift all the low half inputs to the high mask!");
8361
8362   // Do a half shuffle for the low mask.
8363   if (!isNoopShuffleMask(LoMask))
8364     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8365                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8366
8367   // Do a half shuffle with the high mask after shifting its values down.
8368   for (int &M : HiMask)
8369     if (M >= 0)
8370       M -= 4;
8371   if (!isNoopShuffleMask(HiMask))
8372     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8373                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8374
8375   return V;
8376 }
8377
8378 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8379 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8380                                           SDValue V2, ArrayRef<int> Mask,
8381                                           SelectionDAG &DAG, bool &V1InUse,
8382                                           bool &V2InUse) {
8383   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8384   SDValue V1Mask[16];
8385   SDValue V2Mask[16];
8386   V1InUse = false;
8387   V2InUse = false;
8388
8389   int Size = Mask.size();
8390   int Scale = 16 / Size;
8391   for (int i = 0; i < 16; ++i) {
8392     if (Mask[i / Scale] == -1) {
8393       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8394     } else {
8395       const int ZeroMask = 0x80;
8396       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8397                                           : ZeroMask;
8398       int V2Idx = Mask[i / Scale] < Size
8399                       ? ZeroMask
8400                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8401       if (Zeroable[i / Scale])
8402         V1Idx = V2Idx = ZeroMask;
8403       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8404       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8405       V1InUse |= (ZeroMask != V1Idx);
8406       V2InUse |= (ZeroMask != V2Idx);
8407     }
8408   }
8409
8410   if (V1InUse)
8411     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8412                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8413                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8414   if (V2InUse)
8415     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8416                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8417                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8418
8419   // If we need shuffled inputs from both, blend the two.
8420   SDValue V;
8421   if (V1InUse && V2InUse)
8422     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8423   else
8424     V = V1InUse ? V1 : V2;
8425
8426   // Cast the result back to the correct type.
8427   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8428 }
8429
8430 /// \brief Generic lowering of 8-lane i16 shuffles.
8431 ///
8432 /// This handles both single-input shuffles and combined shuffle/blends with
8433 /// two inputs. The single input shuffles are immediately delegated to
8434 /// a dedicated lowering routine.
8435 ///
8436 /// The blends are lowered in one of three fundamental ways. If there are few
8437 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8438 /// of the input is significantly cheaper when lowered as an interleaving of
8439 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8440 /// halves of the inputs separately (making them have relatively few inputs)
8441 /// and then concatenate them.
8442 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8443                                        const X86Subtarget *Subtarget,
8444                                        SelectionDAG &DAG) {
8445   SDLoc DL(Op);
8446   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8447   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8448   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8449   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8450   ArrayRef<int> OrigMask = SVOp->getMask();
8451   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8452                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8453   MutableArrayRef<int> Mask(MaskStorage);
8454
8455   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8456
8457   // Whenever we can lower this as a zext, that instruction is strictly faster
8458   // than any alternative.
8459   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8460           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8461     return ZExt;
8462
8463   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8464   (void)isV1;
8465   auto isV2 = [](int M) { return M >= 8; };
8466
8467   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8468
8469   if (NumV2Inputs == 0) {
8470     // Check for being able to broadcast a single element.
8471     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8472                                                           Mask, Subtarget, DAG))
8473       return Broadcast;
8474
8475     // Try to use shift instructions.
8476     if (SDValue Shift =
8477             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8478       return Shift;
8479
8480     // Use dedicated unpack instructions for masks that match their pattern.
8481     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8482       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8483     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8484       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8485
8486     // Try to use byte rotation instructions.
8487     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8488                                                         Mask, Subtarget, DAG))
8489       return Rotate;
8490
8491     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8492                                                      Subtarget, DAG);
8493   }
8494
8495   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8496          "All single-input shuffles should be canonicalized to be V1-input "
8497          "shuffles.");
8498
8499   // Try to use shift instructions.
8500   if (SDValue Shift =
8501           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8502     return Shift;
8503
8504   // There are special ways we can lower some single-element blends.
8505   if (NumV2Inputs == 1)
8506     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8507                                                          Mask, Subtarget, DAG))
8508       return V;
8509
8510   // We have different paths for blend lowering, but they all must use the
8511   // *exact* same predicate.
8512   bool IsBlendSupported = Subtarget->hasSSE41();
8513   if (IsBlendSupported)
8514     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8515                                                   Subtarget, DAG))
8516       return Blend;
8517
8518   if (SDValue Masked =
8519           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8520     return Masked;
8521
8522   // Use dedicated unpack instructions for masks that match their pattern.
8523   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8524     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8525   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8526     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8527
8528   // Try to use byte rotation instructions.
8529   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8530           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8531     return Rotate;
8532
8533   if (SDValue BitBlend =
8534           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8535     return BitBlend;
8536
8537   if (SDValue Unpack =
8538           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8539     return Unpack;
8540
8541   // If we can't directly blend but can use PSHUFB, that will be better as it
8542   // can both shuffle and set up the inefficient blend.
8543   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8544     bool V1InUse, V2InUse;
8545     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8546                                       V1InUse, V2InUse);
8547   }
8548
8549   // We can always bit-blend if we have to so the fallback strategy is to
8550   // decompose into single-input permutes and blends.
8551   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8552                                                       Mask, DAG);
8553 }
8554
8555 /// \brief Check whether a compaction lowering can be done by dropping even
8556 /// elements and compute how many times even elements must be dropped.
8557 ///
8558 /// This handles shuffles which take every Nth element where N is a power of
8559 /// two. Example shuffle masks:
8560 ///
8561 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8562 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8563 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8564 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8565 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8566 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8567 ///
8568 /// Any of these lanes can of course be undef.
8569 ///
8570 /// This routine only supports N <= 3.
8571 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8572 /// for larger N.
8573 ///
8574 /// \returns N above, or the number of times even elements must be dropped if
8575 /// there is such a number. Otherwise returns zero.
8576 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8577   // Figure out whether we're looping over two inputs or just one.
8578   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8579
8580   // The modulus for the shuffle vector entries is based on whether this is
8581   // a single input or not.
8582   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8583   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8584          "We should only be called with masks with a power-of-2 size!");
8585
8586   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8587
8588   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8589   // and 2^3 simultaneously. This is because we may have ambiguity with
8590   // partially undef inputs.
8591   bool ViableForN[3] = {true, true, true};
8592
8593   for (int i = 0, e = Mask.size(); i < e; ++i) {
8594     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8595     // want.
8596     if (Mask[i] == -1)
8597       continue;
8598
8599     bool IsAnyViable = false;
8600     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8601       if (ViableForN[j]) {
8602         uint64_t N = j + 1;
8603
8604         // The shuffle mask must be equal to (i * 2^N) % M.
8605         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8606           IsAnyViable = true;
8607         else
8608           ViableForN[j] = false;
8609       }
8610     // Early exit if we exhaust the possible powers of two.
8611     if (!IsAnyViable)
8612       break;
8613   }
8614
8615   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8616     if (ViableForN[j])
8617       return j + 1;
8618
8619   // Return 0 as there is no viable power of two.
8620   return 0;
8621 }
8622
8623 /// \brief Generic lowering of v16i8 shuffles.
8624 ///
8625 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8626 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8627 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8628 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8629 /// back together.
8630 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8631                                        const X86Subtarget *Subtarget,
8632                                        SelectionDAG &DAG) {
8633   SDLoc DL(Op);
8634   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8635   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8636   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8637   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8638   ArrayRef<int> Mask = SVOp->getMask();
8639   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8640
8641   // Try to use shift instructions.
8642   if (SDValue Shift =
8643           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8644     return Shift;
8645
8646   // Try to use byte rotation instructions.
8647   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8648           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8649     return Rotate;
8650
8651   // Try to use a zext lowering.
8652   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8653           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8654     return ZExt;
8655
8656   int NumV2Elements =
8657       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8658
8659   // For single-input shuffles, there are some nicer lowering tricks we can use.
8660   if (NumV2Elements == 0) {
8661     // Check for being able to broadcast a single element.
8662     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8663                                                           Mask, Subtarget, DAG))
8664       return Broadcast;
8665
8666     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8667     // Notably, this handles splat and partial-splat shuffles more efficiently.
8668     // However, it only makes sense if the pre-duplication shuffle simplifies
8669     // things significantly. Currently, this means we need to be able to
8670     // express the pre-duplication shuffle as an i16 shuffle.
8671     //
8672     // FIXME: We should check for other patterns which can be widened into an
8673     // i16 shuffle as well.
8674     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8675       for (int i = 0; i < 16; i += 2)
8676         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8677           return false;
8678
8679       return true;
8680     };
8681     auto tryToWidenViaDuplication = [&]() -> SDValue {
8682       if (!canWidenViaDuplication(Mask))
8683         return SDValue();
8684       SmallVector<int, 4> LoInputs;
8685       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8686                    [](int M) { return M >= 0 && M < 8; });
8687       std::sort(LoInputs.begin(), LoInputs.end());
8688       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8689                      LoInputs.end());
8690       SmallVector<int, 4> HiInputs;
8691       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8692                    [](int M) { return M >= 8; });
8693       std::sort(HiInputs.begin(), HiInputs.end());
8694       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8695                      HiInputs.end());
8696
8697       bool TargetLo = LoInputs.size() >= HiInputs.size();
8698       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8699       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8700
8701       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8702       SmallDenseMap<int, int, 8> LaneMap;
8703       for (int I : InPlaceInputs) {
8704         PreDupI16Shuffle[I/2] = I/2;
8705         LaneMap[I] = I;
8706       }
8707       int j = TargetLo ? 0 : 4, je = j + 4;
8708       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8709         // Check if j is already a shuffle of this input. This happens when
8710         // there are two adjacent bytes after we move the low one.
8711         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8712           // If we haven't yet mapped the input, search for a slot into which
8713           // we can map it.
8714           while (j < je && PreDupI16Shuffle[j] != -1)
8715             ++j;
8716
8717           if (j == je)
8718             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8719             return SDValue();
8720
8721           // Map this input with the i16 shuffle.
8722           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8723         }
8724
8725         // Update the lane map based on the mapping we ended up with.
8726         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8727       }
8728       V1 = DAG.getNode(
8729           ISD::BITCAST, DL, MVT::v16i8,
8730           DAG.getVectorShuffle(MVT::v8i16, DL,
8731                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8732                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8733
8734       // Unpack the bytes to form the i16s that will be shuffled into place.
8735       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8736                        MVT::v16i8, V1, V1);
8737
8738       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8739       for (int i = 0; i < 16; ++i)
8740         if (Mask[i] != -1) {
8741           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8742           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8743           if (PostDupI16Shuffle[i / 2] == -1)
8744             PostDupI16Shuffle[i / 2] = MappedMask;
8745           else
8746             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8747                    "Conflicting entrties in the original shuffle!");
8748         }
8749       return DAG.getNode(
8750           ISD::BITCAST, DL, MVT::v16i8,
8751           DAG.getVectorShuffle(MVT::v8i16, DL,
8752                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8753                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8754     };
8755     if (SDValue V = tryToWidenViaDuplication())
8756       return V;
8757   }
8758
8759   // Use dedicated unpack instructions for masks that match their pattern.
8760   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8761                                          0, 16, 1, 17, 2, 18, 3, 19,
8762                                          // High half.
8763                                          4, 20, 5, 21, 6, 22, 7, 23}))
8764     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8765   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8766                                          8, 24, 9, 25, 10, 26, 11, 27,
8767                                          // High half.
8768                                          12, 28, 13, 29, 14, 30, 15, 31}))
8769     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8770
8771   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8772   // with PSHUFB. It is important to do this before we attempt to generate any
8773   // blends but after all of the single-input lowerings. If the single input
8774   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8775   // want to preserve that and we can DAG combine any longer sequences into
8776   // a PSHUFB in the end. But once we start blending from multiple inputs,
8777   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8778   // and there are *very* few patterns that would actually be faster than the
8779   // PSHUFB approach because of its ability to zero lanes.
8780   //
8781   // FIXME: The only exceptions to the above are blends which are exact
8782   // interleavings with direct instructions supporting them. We currently don't
8783   // handle those well here.
8784   if (Subtarget->hasSSSE3()) {
8785     bool V1InUse = false;
8786     bool V2InUse = false;
8787
8788     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8789                                                 DAG, V1InUse, V2InUse);
8790
8791     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8792     // do so. This avoids using them to handle blends-with-zero which is
8793     // important as a single pshufb is significantly faster for that.
8794     if (V1InUse && V2InUse) {
8795       if (Subtarget->hasSSE41())
8796         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8797                                                       Mask, Subtarget, DAG))
8798           return Blend;
8799
8800       // We can use an unpack to do the blending rather than an or in some
8801       // cases. Even though the or may be (very minorly) more efficient, we
8802       // preference this lowering because there are common cases where part of
8803       // the complexity of the shuffles goes away when we do the final blend as
8804       // an unpack.
8805       // FIXME: It might be worth trying to detect if the unpack-feeding
8806       // shuffles will both be pshufb, in which case we shouldn't bother with
8807       // this.
8808       if (SDValue Unpack =
8809               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8810         return Unpack;
8811     }
8812
8813     return PSHUFB;
8814   }
8815
8816   // There are special ways we can lower some single-element blends.
8817   if (NumV2Elements == 1)
8818     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8819                                                          Mask, Subtarget, DAG))
8820       return V;
8821
8822   if (SDValue BitBlend =
8823           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8824     return BitBlend;
8825
8826   // Check whether a compaction lowering can be done. This handles shuffles
8827   // which take every Nth element for some even N. See the helper function for
8828   // details.
8829   //
8830   // We special case these as they can be particularly efficiently handled with
8831   // the PACKUSB instruction on x86 and they show up in common patterns of
8832   // rearranging bytes to truncate wide elements.
8833   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8834     // NumEvenDrops is the power of two stride of the elements. Another way of
8835     // thinking about it is that we need to drop the even elements this many
8836     // times to get the original input.
8837     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8838
8839     // First we need to zero all the dropped bytes.
8840     assert(NumEvenDrops <= 3 &&
8841            "No support for dropping even elements more than 3 times.");
8842     // We use the mask type to pick which bytes are preserved based on how many
8843     // elements are dropped.
8844     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8845     SDValue ByteClearMask =
8846         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8847                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8848     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8849     if (!IsSingleInput)
8850       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8851
8852     // Now pack things back together.
8853     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8854     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8855     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8856     for (int i = 1; i < NumEvenDrops; ++i) {
8857       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8858       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8859     }
8860
8861     return Result;
8862   }
8863
8864   // Handle multi-input cases by blending single-input shuffles.
8865   if (NumV2Elements > 0)
8866     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8867                                                       Mask, DAG);
8868
8869   // The fallback path for single-input shuffles widens this into two v8i16
8870   // vectors with unpacks, shuffles those, and then pulls them back together
8871   // with a pack.
8872   SDValue V = V1;
8873
8874   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8875   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8876   for (int i = 0; i < 16; ++i)
8877     if (Mask[i] >= 0)
8878       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8879
8880   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8881
8882   SDValue VLoHalf, VHiHalf;
8883   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8884   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8885   // i16s.
8886   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8887                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8888       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8889                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8890     // Use a mask to drop the high bytes.
8891     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8892     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8893                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8894
8895     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8896     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8897
8898     // Squash the masks to point directly into VLoHalf.
8899     for (int &M : LoBlendMask)
8900       if (M >= 0)
8901         M /= 2;
8902     for (int &M : HiBlendMask)
8903       if (M >= 0)
8904         M /= 2;
8905   } else {
8906     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8907     // VHiHalf so that we can blend them as i16s.
8908     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8909                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8910     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8911                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8912   }
8913
8914   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8915   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8916
8917   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8918 }
8919
8920 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8921 ///
8922 /// This routine breaks down the specific type of 128-bit shuffle and
8923 /// dispatches to the lowering routines accordingly.
8924 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8925                                         MVT VT, const X86Subtarget *Subtarget,
8926                                         SelectionDAG &DAG) {
8927   switch (VT.SimpleTy) {
8928   case MVT::v2i64:
8929     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8930   case MVT::v2f64:
8931     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8932   case MVT::v4i32:
8933     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8934   case MVT::v4f32:
8935     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8936   case MVT::v8i16:
8937     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8938   case MVT::v16i8:
8939     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8940
8941   default:
8942     llvm_unreachable("Unimplemented!");
8943   }
8944 }
8945
8946 /// \brief Helper function to test whether a shuffle mask could be
8947 /// simplified by widening the elements being shuffled.
8948 ///
8949 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8950 /// leaves it in an unspecified state.
8951 ///
8952 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8953 /// shuffle masks. The latter have the special property of a '-2' representing
8954 /// a zero-ed lane of a vector.
8955 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8956                                     SmallVectorImpl<int> &WidenedMask) {
8957   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8958     // If both elements are undef, its trivial.
8959     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8960       WidenedMask.push_back(SM_SentinelUndef);
8961       continue;
8962     }
8963
8964     // Check for an undef mask and a mask value properly aligned to fit with
8965     // a pair of values. If we find such a case, use the non-undef mask's value.
8966     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8967       WidenedMask.push_back(Mask[i + 1] / 2);
8968       continue;
8969     }
8970     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8971       WidenedMask.push_back(Mask[i] / 2);
8972       continue;
8973     }
8974
8975     // When zeroing, we need to spread the zeroing across both lanes to widen.
8976     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8977       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8978           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8979         WidenedMask.push_back(SM_SentinelZero);
8980         continue;
8981       }
8982       return false;
8983     }
8984
8985     // Finally check if the two mask values are adjacent and aligned with
8986     // a pair.
8987     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8988       WidenedMask.push_back(Mask[i] / 2);
8989       continue;
8990     }
8991
8992     // Otherwise we can't safely widen the elements used in this shuffle.
8993     return false;
8994   }
8995   assert(WidenedMask.size() == Mask.size() / 2 &&
8996          "Incorrect size of mask after widening the elements!");
8997
8998   return true;
8999 }
9000
9001 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9002 ///
9003 /// This routine just extracts two subvectors, shuffles them independently, and
9004 /// then concatenates them back together. This should work effectively with all
9005 /// AVX vector shuffle types.
9006 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9007                                           SDValue V2, ArrayRef<int> Mask,
9008                                           SelectionDAG &DAG) {
9009   assert(VT.getSizeInBits() >= 256 &&
9010          "Only for 256-bit or wider vector shuffles!");
9011   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9012   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9013
9014   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9015   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9016
9017   int NumElements = VT.getVectorNumElements();
9018   int SplitNumElements = NumElements / 2;
9019   MVT ScalarVT = VT.getScalarType();
9020   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9021
9022   // Rather than splitting build-vectors, just build two narrower build
9023   // vectors. This helps shuffling with splats and zeros.
9024   auto SplitVector = [&](SDValue V) {
9025     while (V.getOpcode() == ISD::BITCAST)
9026       V = V->getOperand(0);
9027
9028     MVT OrigVT = V.getSimpleValueType();
9029     int OrigNumElements = OrigVT.getVectorNumElements();
9030     int OrigSplitNumElements = OrigNumElements / 2;
9031     MVT OrigScalarVT = OrigVT.getScalarType();
9032     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9033
9034     SDValue LoV, HiV;
9035
9036     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9037     if (!BV) {
9038       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9039                         DAG.getIntPtrConstant(0, DL));
9040       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9041                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9042     } else {
9043
9044       SmallVector<SDValue, 16> LoOps, HiOps;
9045       for (int i = 0; i < OrigSplitNumElements; ++i) {
9046         LoOps.push_back(BV->getOperand(i));
9047         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9048       }
9049       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9050       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9051     }
9052     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9053                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9054   };
9055
9056   SDValue LoV1, HiV1, LoV2, HiV2;
9057   std::tie(LoV1, HiV1) = SplitVector(V1);
9058   std::tie(LoV2, HiV2) = SplitVector(V2);
9059
9060   // Now create two 4-way blends of these half-width vectors.
9061   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9062     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9063     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9064     for (int i = 0; i < SplitNumElements; ++i) {
9065       int M = HalfMask[i];
9066       if (M >= NumElements) {
9067         if (M >= NumElements + SplitNumElements)
9068           UseHiV2 = true;
9069         else
9070           UseLoV2 = true;
9071         V2BlendMask.push_back(M - NumElements);
9072         V1BlendMask.push_back(-1);
9073         BlendMask.push_back(SplitNumElements + i);
9074       } else if (M >= 0) {
9075         if (M >= SplitNumElements)
9076           UseHiV1 = true;
9077         else
9078           UseLoV1 = true;
9079         V2BlendMask.push_back(-1);
9080         V1BlendMask.push_back(M);
9081         BlendMask.push_back(i);
9082       } else {
9083         V2BlendMask.push_back(-1);
9084         V1BlendMask.push_back(-1);
9085         BlendMask.push_back(-1);
9086       }
9087     }
9088
9089     // Because the lowering happens after all combining takes place, we need to
9090     // manually combine these blend masks as much as possible so that we create
9091     // a minimal number of high-level vector shuffle nodes.
9092
9093     // First try just blending the halves of V1 or V2.
9094     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9095       return DAG.getUNDEF(SplitVT);
9096     if (!UseLoV2 && !UseHiV2)
9097       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9098     if (!UseLoV1 && !UseHiV1)
9099       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9100
9101     SDValue V1Blend, V2Blend;
9102     if (UseLoV1 && UseHiV1) {
9103       V1Blend =
9104         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9105     } else {
9106       // We only use half of V1 so map the usage down into the final blend mask.
9107       V1Blend = UseLoV1 ? LoV1 : HiV1;
9108       for (int i = 0; i < SplitNumElements; ++i)
9109         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9110           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9111     }
9112     if (UseLoV2 && UseHiV2) {
9113       V2Blend =
9114         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9115     } else {
9116       // We only use half of V2 so map the usage down into the final blend mask.
9117       V2Blend = UseLoV2 ? LoV2 : HiV2;
9118       for (int i = 0; i < SplitNumElements; ++i)
9119         if (BlendMask[i] >= SplitNumElements)
9120           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9121     }
9122     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9123   };
9124   SDValue Lo = HalfBlend(LoMask);
9125   SDValue Hi = HalfBlend(HiMask);
9126   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9127 }
9128
9129 /// \brief Either split a vector in halves or decompose the shuffles and the
9130 /// blend.
9131 ///
9132 /// This is provided as a good fallback for many lowerings of non-single-input
9133 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9134 /// between splitting the shuffle into 128-bit components and stitching those
9135 /// back together vs. extracting the single-input shuffles and blending those
9136 /// results.
9137 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9138                                                 SDValue V2, ArrayRef<int> Mask,
9139                                                 SelectionDAG &DAG) {
9140   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9141                                             "lower single-input shuffles as it "
9142                                             "could then recurse on itself.");
9143   int Size = Mask.size();
9144
9145   // If this can be modeled as a broadcast of two elements followed by a blend,
9146   // prefer that lowering. This is especially important because broadcasts can
9147   // often fold with memory operands.
9148   auto DoBothBroadcast = [&] {
9149     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9150     for (int M : Mask)
9151       if (M >= Size) {
9152         if (V2BroadcastIdx == -1)
9153           V2BroadcastIdx = M - Size;
9154         else if (M - Size != V2BroadcastIdx)
9155           return false;
9156       } else if (M >= 0) {
9157         if (V1BroadcastIdx == -1)
9158           V1BroadcastIdx = M;
9159         else if (M != V1BroadcastIdx)
9160           return false;
9161       }
9162     return true;
9163   };
9164   if (DoBothBroadcast())
9165     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9166                                                       DAG);
9167
9168   // If the inputs all stem from a single 128-bit lane of each input, then we
9169   // split them rather than blending because the split will decompose to
9170   // unusually few instructions.
9171   int LaneCount = VT.getSizeInBits() / 128;
9172   int LaneSize = Size / LaneCount;
9173   SmallBitVector LaneInputs[2];
9174   LaneInputs[0].resize(LaneCount, false);
9175   LaneInputs[1].resize(LaneCount, false);
9176   for (int i = 0; i < Size; ++i)
9177     if (Mask[i] >= 0)
9178       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9179   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9180     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9181
9182   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9183   // that the decomposed single-input shuffles don't end up here.
9184   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9185 }
9186
9187 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9188 /// a permutation and blend of those lanes.
9189 ///
9190 /// This essentially blends the out-of-lane inputs to each lane into the lane
9191 /// from a permuted copy of the vector. This lowering strategy results in four
9192 /// instructions in the worst case for a single-input cross lane shuffle which
9193 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9194 /// of. Special cases for each particular shuffle pattern should be handled
9195 /// prior to trying this lowering.
9196 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9197                                                        SDValue V1, SDValue V2,
9198                                                        ArrayRef<int> Mask,
9199                                                        SelectionDAG &DAG) {
9200   // FIXME: This should probably be generalized for 512-bit vectors as well.
9201   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9202   int LaneSize = Mask.size() / 2;
9203
9204   // If there are only inputs from one 128-bit lane, splitting will in fact be
9205   // less expensive. The flags track whether the given lane contains an element
9206   // that crosses to another lane.
9207   bool LaneCrossing[2] = {false, false};
9208   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9209     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9210       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9211   if (!LaneCrossing[0] || !LaneCrossing[1])
9212     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9213
9214   if (isSingleInputShuffleMask(Mask)) {
9215     SmallVector<int, 32> FlippedBlendMask;
9216     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9217       FlippedBlendMask.push_back(
9218           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9219                                   ? Mask[i]
9220                                   : Mask[i] % LaneSize +
9221                                         (i / LaneSize) * LaneSize + Size));
9222
9223     // Flip the vector, and blend the results which should now be in-lane. The
9224     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9225     // 5 for the high source. The value 3 selects the high half of source 2 and
9226     // the value 2 selects the low half of source 2. We only use source 2 to
9227     // allow folding it into a memory operand.
9228     unsigned PERMMask = 3 | 2 << 4;
9229     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9230                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9231     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9232   }
9233
9234   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9235   // will be handled by the above logic and a blend of the results, much like
9236   // other patterns in AVX.
9237   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9238 }
9239
9240 /// \brief Handle lowering 2-lane 128-bit shuffles.
9241 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9242                                         SDValue V2, ArrayRef<int> Mask,
9243                                         const X86Subtarget *Subtarget,
9244                                         SelectionDAG &DAG) {
9245   // TODO: If minimizing size and one of the inputs is a zero vector and the
9246   // the zero vector has only one use, we could use a VPERM2X128 to save the
9247   // instruction bytes needed to explicitly generate the zero vector.
9248
9249   // Blends are faster and handle all the non-lane-crossing cases.
9250   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9251                                                 Subtarget, DAG))
9252     return Blend;
9253
9254   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9255   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9256
9257   // If either input operand is a zero vector, use VPERM2X128 because its mask
9258   // allows us to replace the zero input with an implicit zero.
9259   if (!IsV1Zero && !IsV2Zero) {
9260     // Check for patterns which can be matched with a single insert of a 128-bit
9261     // subvector.
9262     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9263     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9264       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9265                                    VT.getVectorNumElements() / 2);
9266       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9267                                 DAG.getIntPtrConstant(0, DL));
9268       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9269                                 OnlyUsesV1 ? V1 : V2,
9270                                 DAG.getIntPtrConstant(0, DL));
9271       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9272     }
9273   }
9274
9275   // Otherwise form a 128-bit permutation. After accounting for undefs,
9276   // convert the 64-bit shuffle mask selection values into 128-bit
9277   // selection bits by dividing the indexes by 2 and shifting into positions
9278   // defined by a vperm2*128 instruction's immediate control byte.
9279
9280   // The immediate permute control byte looks like this:
9281   //    [1:0] - select 128 bits from sources for low half of destination
9282   //    [2]   - ignore
9283   //    [3]   - zero low half of destination
9284   //    [5:4] - select 128 bits from sources for high half of destination
9285   //    [6]   - ignore
9286   //    [7]   - zero high half of destination
9287
9288   int MaskLO = Mask[0];
9289   if (MaskLO == SM_SentinelUndef)
9290     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9291
9292   int MaskHI = Mask[2];
9293   if (MaskHI == SM_SentinelUndef)
9294     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9295
9296   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9297
9298   // If either input is a zero vector, replace it with an undef input.
9299   // Shuffle mask values <  4 are selecting elements of V1.
9300   // Shuffle mask values >= 4 are selecting elements of V2.
9301   // Adjust each half of the permute mask by clearing the half that was
9302   // selecting the zero vector and setting the zero mask bit.
9303   if (IsV1Zero) {
9304     V1 = DAG.getUNDEF(VT);
9305     if (MaskLO < 4)
9306       PermMask = (PermMask & 0xf0) | 0x08;
9307     if (MaskHI < 4)
9308       PermMask = (PermMask & 0x0f) | 0x80;
9309   }
9310   if (IsV2Zero) {
9311     V2 = DAG.getUNDEF(VT);
9312     if (MaskLO >= 4)
9313       PermMask = (PermMask & 0xf0) | 0x08;
9314     if (MaskHI >= 4)
9315       PermMask = (PermMask & 0x0f) | 0x80;
9316   }
9317
9318   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9319                      DAG.getConstant(PermMask, DL, MVT::i8));
9320 }
9321
9322 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9323 /// shuffling each lane.
9324 ///
9325 /// This will only succeed when the result of fixing the 128-bit lanes results
9326 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9327 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9328 /// the lane crosses early and then use simpler shuffles within each lane.
9329 ///
9330 /// FIXME: It might be worthwhile at some point to support this without
9331 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9332 /// in x86 only floating point has interesting non-repeating shuffles, and even
9333 /// those are still *marginally* more expensive.
9334 static SDValue lowerVectorShuffleByMerging128BitLanes(
9335     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9336     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9337   assert(!isSingleInputShuffleMask(Mask) &&
9338          "This is only useful with multiple inputs.");
9339
9340   int Size = Mask.size();
9341   int LaneSize = 128 / VT.getScalarSizeInBits();
9342   int NumLanes = Size / LaneSize;
9343   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9344
9345   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9346   // check whether the in-128-bit lane shuffles share a repeating pattern.
9347   SmallVector<int, 4> Lanes;
9348   Lanes.resize(NumLanes, -1);
9349   SmallVector<int, 4> InLaneMask;
9350   InLaneMask.resize(LaneSize, -1);
9351   for (int i = 0; i < Size; ++i) {
9352     if (Mask[i] < 0)
9353       continue;
9354
9355     int j = i / LaneSize;
9356
9357     if (Lanes[j] < 0) {
9358       // First entry we've seen for this lane.
9359       Lanes[j] = Mask[i] / LaneSize;
9360     } else if (Lanes[j] != Mask[i] / LaneSize) {
9361       // This doesn't match the lane selected previously!
9362       return SDValue();
9363     }
9364
9365     // Check that within each lane we have a consistent shuffle mask.
9366     int k = i % LaneSize;
9367     if (InLaneMask[k] < 0) {
9368       InLaneMask[k] = Mask[i] % LaneSize;
9369     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9370       // This doesn't fit a repeating in-lane mask.
9371       return SDValue();
9372     }
9373   }
9374
9375   // First shuffle the lanes into place.
9376   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9377                                 VT.getSizeInBits() / 64);
9378   SmallVector<int, 8> LaneMask;
9379   LaneMask.resize(NumLanes * 2, -1);
9380   for (int i = 0; i < NumLanes; ++i)
9381     if (Lanes[i] >= 0) {
9382       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9383       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9384     }
9385
9386   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9387   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9388   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9389
9390   // Cast it back to the type we actually want.
9391   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9392
9393   // Now do a simple shuffle that isn't lane crossing.
9394   SmallVector<int, 8> NewMask;
9395   NewMask.resize(Size, -1);
9396   for (int i = 0; i < Size; ++i)
9397     if (Mask[i] >= 0)
9398       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9399   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9400          "Must not introduce lane crosses at this point!");
9401
9402   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9403 }
9404
9405 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9406 /// given mask.
9407 ///
9408 /// This returns true if the elements from a particular input are already in the
9409 /// slot required by the given mask and require no permutation.
9410 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9411   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9412   int Size = Mask.size();
9413   for (int i = 0; i < Size; ++i)
9414     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9415       return false;
9416
9417   return true;
9418 }
9419
9420 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9421 ///
9422 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9423 /// isn't available.
9424 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9425                                        const X86Subtarget *Subtarget,
9426                                        SelectionDAG &DAG) {
9427   SDLoc DL(Op);
9428   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9429   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9430   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9431   ArrayRef<int> Mask = SVOp->getMask();
9432   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9433
9434   SmallVector<int, 4> WidenedMask;
9435   if (canWidenShuffleElements(Mask, WidenedMask))
9436     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9437                                     DAG);
9438
9439   if (isSingleInputShuffleMask(Mask)) {
9440     // Check for being able to broadcast a single element.
9441     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9442                                                           Mask, Subtarget, DAG))
9443       return Broadcast;
9444
9445     // Use low duplicate instructions for masks that match their pattern.
9446     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9447       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9448
9449     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9450       // Non-half-crossing single input shuffles can be lowerid with an
9451       // interleaved permutation.
9452       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9453                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9454       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9455                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9456     }
9457
9458     // With AVX2 we have direct support for this permutation.
9459     if (Subtarget->hasAVX2())
9460       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9461                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9462
9463     // Otherwise, fall back.
9464     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9465                                                    DAG);
9466   }
9467
9468   // X86 has dedicated unpack instructions that can handle specific blend
9469   // operations: UNPCKH and UNPCKL.
9470   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9471     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9472   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9473     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9474   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9475     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9476   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9477     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9478
9479   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9480                                                 Subtarget, DAG))
9481     return Blend;
9482
9483   // Check if the blend happens to exactly fit that of SHUFPD.
9484   if ((Mask[0] == -1 || Mask[0] < 2) &&
9485       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9486       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9487       (Mask[3] == -1 || Mask[3] >= 6)) {
9488     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9489                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9490     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9491                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9492   }
9493   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9494       (Mask[1] == -1 || Mask[1] < 2) &&
9495       (Mask[2] == -1 || Mask[2] >= 6) &&
9496       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9497     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9498                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9499     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9500                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9501   }
9502
9503   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9504   // shuffle. However, if we have AVX2 and either inputs are already in place,
9505   // we will be able to shuffle even across lanes the other input in a single
9506   // instruction so skip this pattern.
9507   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9508                                  isShuffleMaskInputInPlace(1, Mask))))
9509     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9510             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9511       return Result;
9512
9513   // If we have AVX2 then we always want to lower with a blend because an v4 we
9514   // can fully permute the elements.
9515   if (Subtarget->hasAVX2())
9516     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9517                                                       Mask, DAG);
9518
9519   // Otherwise fall back on generic lowering.
9520   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9521 }
9522
9523 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9524 ///
9525 /// This routine is only called when we have AVX2 and thus a reasonable
9526 /// instruction set for v4i64 shuffling..
9527 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9528                                        const X86Subtarget *Subtarget,
9529                                        SelectionDAG &DAG) {
9530   SDLoc DL(Op);
9531   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9532   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9533   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9534   ArrayRef<int> Mask = SVOp->getMask();
9535   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9536   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9537
9538   SmallVector<int, 4> WidenedMask;
9539   if (canWidenShuffleElements(Mask, WidenedMask))
9540     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9541                                     DAG);
9542
9543   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9544                                                 Subtarget, DAG))
9545     return Blend;
9546
9547   // Check for being able to broadcast a single element.
9548   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9549                                                         Mask, Subtarget, DAG))
9550     return Broadcast;
9551
9552   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9553   // use lower latency instructions that will operate on both 128-bit lanes.
9554   SmallVector<int, 2> RepeatedMask;
9555   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9556     if (isSingleInputShuffleMask(Mask)) {
9557       int PSHUFDMask[] = {-1, -1, -1, -1};
9558       for (int i = 0; i < 2; ++i)
9559         if (RepeatedMask[i] >= 0) {
9560           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9561           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9562         }
9563       return DAG.getNode(
9564           ISD::BITCAST, DL, MVT::v4i64,
9565           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9566                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9567                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9568     }
9569   }
9570
9571   // AVX2 provides a direct instruction for permuting a single input across
9572   // lanes.
9573   if (isSingleInputShuffleMask(Mask))
9574     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9575                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9576
9577   // Try to use shift instructions.
9578   if (SDValue Shift =
9579           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9580     return Shift;
9581
9582   // Use dedicated unpack instructions for masks that match their pattern.
9583   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9584     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9585   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9586     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9587   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9588     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9589   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9590     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9591
9592   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9593   // shuffle. However, if we have AVX2 and either inputs are already in place,
9594   // we will be able to shuffle even across lanes the other input in a single
9595   // instruction so skip this pattern.
9596   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9597                                  isShuffleMaskInputInPlace(1, Mask))))
9598     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9599             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9600       return Result;
9601
9602   // Otherwise fall back on generic blend lowering.
9603   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9604                                                     Mask, DAG);
9605 }
9606
9607 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9608 ///
9609 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9610 /// isn't available.
9611 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9612                                        const X86Subtarget *Subtarget,
9613                                        SelectionDAG &DAG) {
9614   SDLoc DL(Op);
9615   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9616   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9617   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9618   ArrayRef<int> Mask = SVOp->getMask();
9619   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9620
9621   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9622                                                 Subtarget, DAG))
9623     return Blend;
9624
9625   // Check for being able to broadcast a single element.
9626   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9627                                                         Mask, Subtarget, DAG))
9628     return Broadcast;
9629
9630   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9631   // options to efficiently lower the shuffle.
9632   SmallVector<int, 4> RepeatedMask;
9633   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9634     assert(RepeatedMask.size() == 4 &&
9635            "Repeated masks must be half the mask width!");
9636
9637     // Use even/odd duplicate instructions for masks that match their pattern.
9638     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9639       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9640     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9641       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9642
9643     if (isSingleInputShuffleMask(Mask))
9644       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9645                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9646
9647     // Use dedicated unpack instructions for masks that match their pattern.
9648     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9649       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9650     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9651       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9652     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9653       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9654     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9655       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9656
9657     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9658     // have already handled any direct blends. We also need to squash the
9659     // repeated mask into a simulated v4f32 mask.
9660     for (int i = 0; i < 4; ++i)
9661       if (RepeatedMask[i] >= 8)
9662         RepeatedMask[i] -= 4;
9663     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9664   }
9665
9666   // If we have a single input shuffle with different shuffle patterns in the
9667   // two 128-bit lanes use the variable mask to VPERMILPS.
9668   if (isSingleInputShuffleMask(Mask)) {
9669     SDValue VPermMask[8];
9670     for (int i = 0; i < 8; ++i)
9671       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9672                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9673     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9674       return DAG.getNode(
9675           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9676           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9677
9678     if (Subtarget->hasAVX2())
9679       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9680                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9681                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9682                                                  MVT::v8i32, VPermMask)),
9683                          V1);
9684
9685     // Otherwise, fall back.
9686     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9687                                                    DAG);
9688   }
9689
9690   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9691   // shuffle.
9692   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9693           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9694     return Result;
9695
9696   // If we have AVX2 then we always want to lower with a blend because at v8 we
9697   // can fully permute the elements.
9698   if (Subtarget->hasAVX2())
9699     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9700                                                       Mask, DAG);
9701
9702   // Otherwise fall back on generic lowering.
9703   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9704 }
9705
9706 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9707 ///
9708 /// This routine is only called when we have AVX2 and thus a reasonable
9709 /// instruction set for v8i32 shuffling..
9710 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9711                                        const X86Subtarget *Subtarget,
9712                                        SelectionDAG &DAG) {
9713   SDLoc DL(Op);
9714   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9715   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9716   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9717   ArrayRef<int> Mask = SVOp->getMask();
9718   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9719   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9720
9721   // Whenever we can lower this as a zext, that instruction is strictly faster
9722   // than any alternative. It also allows us to fold memory operands into the
9723   // shuffle in many cases.
9724   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9725                                                          Mask, Subtarget, DAG))
9726     return ZExt;
9727
9728   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9729                                                 Subtarget, DAG))
9730     return Blend;
9731
9732   // Check for being able to broadcast a single element.
9733   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9734                                                         Mask, Subtarget, DAG))
9735     return Broadcast;
9736
9737   // If the shuffle mask is repeated in each 128-bit lane we can use more
9738   // efficient instructions that mirror the shuffles across the two 128-bit
9739   // lanes.
9740   SmallVector<int, 4> RepeatedMask;
9741   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9742     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9743     if (isSingleInputShuffleMask(Mask))
9744       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9745                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9746
9747     // Use dedicated unpack instructions for masks that match their pattern.
9748     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9749       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9750     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9751       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9752     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9753       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9754     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9755       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9756   }
9757
9758   // Try to use shift instructions.
9759   if (SDValue Shift =
9760           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9761     return Shift;
9762
9763   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9764           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9765     return Rotate;
9766
9767   // If the shuffle patterns aren't repeated but it is a single input, directly
9768   // generate a cross-lane VPERMD instruction.
9769   if (isSingleInputShuffleMask(Mask)) {
9770     SDValue VPermMask[8];
9771     for (int i = 0; i < 8; ++i)
9772       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9773                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9774     return DAG.getNode(
9775         X86ISD::VPERMV, DL, MVT::v8i32,
9776         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9777   }
9778
9779   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9780   // shuffle.
9781   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9782           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9783     return Result;
9784
9785   // Otherwise fall back on generic blend lowering.
9786   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9787                                                     Mask, DAG);
9788 }
9789
9790 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9791 ///
9792 /// This routine is only called when we have AVX2 and thus a reasonable
9793 /// instruction set for v16i16 shuffling..
9794 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9795                                         const X86Subtarget *Subtarget,
9796                                         SelectionDAG &DAG) {
9797   SDLoc DL(Op);
9798   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9799   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9800   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9801   ArrayRef<int> Mask = SVOp->getMask();
9802   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9803   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9804
9805   // Whenever we can lower this as a zext, that instruction is strictly faster
9806   // than any alternative. It also allows us to fold memory operands into the
9807   // shuffle in many cases.
9808   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9809                                                          Mask, Subtarget, DAG))
9810     return ZExt;
9811
9812   // Check for being able to broadcast a single element.
9813   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9814                                                         Mask, Subtarget, DAG))
9815     return Broadcast;
9816
9817   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9818                                                 Subtarget, DAG))
9819     return Blend;
9820
9821   // Use dedicated unpack instructions for masks that match their pattern.
9822   if (isShuffleEquivalent(V1, V2, Mask,
9823                           {// First 128-bit lane:
9824                            0, 16, 1, 17, 2, 18, 3, 19,
9825                            // Second 128-bit lane:
9826                            8, 24, 9, 25, 10, 26, 11, 27}))
9827     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9828   if (isShuffleEquivalent(V1, V2, Mask,
9829                           {// First 128-bit lane:
9830                            4, 20, 5, 21, 6, 22, 7, 23,
9831                            // Second 128-bit lane:
9832                            12, 28, 13, 29, 14, 30, 15, 31}))
9833     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9834
9835   // Try to use shift instructions.
9836   if (SDValue Shift =
9837           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9838     return Shift;
9839
9840   // Try to use byte rotation instructions.
9841   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9842           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9843     return Rotate;
9844
9845   if (isSingleInputShuffleMask(Mask)) {
9846     // There are no generalized cross-lane shuffle operations available on i16
9847     // element types.
9848     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9849       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9850                                                      Mask, DAG);
9851
9852     SmallVector<int, 8> RepeatedMask;
9853     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9854       // As this is a single-input shuffle, the repeated mask should be
9855       // a strictly valid v8i16 mask that we can pass through to the v8i16
9856       // lowering to handle even the v16 case.
9857       return lowerV8I16GeneralSingleInputVectorShuffle(
9858           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9859     }
9860
9861     SDValue PSHUFBMask[32];
9862     for (int i = 0; i < 16; ++i) {
9863       if (Mask[i] == -1) {
9864         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9865         continue;
9866       }
9867
9868       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9869       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9870       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9871       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9872     }
9873     return DAG.getNode(
9874         ISD::BITCAST, DL, MVT::v16i16,
9875         DAG.getNode(
9876             X86ISD::PSHUFB, DL, MVT::v32i8,
9877             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9878             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9879   }
9880
9881   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9882   // shuffle.
9883   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9884           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9885     return Result;
9886
9887   // Otherwise fall back on generic lowering.
9888   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9889 }
9890
9891 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9892 ///
9893 /// This routine is only called when we have AVX2 and thus a reasonable
9894 /// instruction set for v32i8 shuffling..
9895 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9896                                        const X86Subtarget *Subtarget,
9897                                        SelectionDAG &DAG) {
9898   SDLoc DL(Op);
9899   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9900   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9901   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9902   ArrayRef<int> Mask = SVOp->getMask();
9903   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9904   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9905
9906   // Whenever we can lower this as a zext, that instruction is strictly faster
9907   // than any alternative. It also allows us to fold memory operands into the
9908   // shuffle in many cases.
9909   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9910                                                          Mask, Subtarget, DAG))
9911     return ZExt;
9912
9913   // Check for being able to broadcast a single element.
9914   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9915                                                         Mask, Subtarget, DAG))
9916     return Broadcast;
9917
9918   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9919                                                 Subtarget, DAG))
9920     return Blend;
9921
9922   // Use dedicated unpack instructions for masks that match their pattern.
9923   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9924   // 256-bit lanes.
9925   if (isShuffleEquivalent(
9926           V1, V2, Mask,
9927           {// First 128-bit lane:
9928            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9929            // Second 128-bit lane:
9930            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9931     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9932   if (isShuffleEquivalent(
9933           V1, V2, Mask,
9934           {// First 128-bit lane:
9935            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9936            // Second 128-bit lane:
9937            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9938     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9939
9940   // Try to use shift instructions.
9941   if (SDValue Shift =
9942           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9943     return Shift;
9944
9945   // Try to use byte rotation instructions.
9946   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9947           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9948     return Rotate;
9949
9950   if (isSingleInputShuffleMask(Mask)) {
9951     // There are no generalized cross-lane shuffle operations available on i8
9952     // element types.
9953     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9954       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9955                                                      Mask, DAG);
9956
9957     SDValue PSHUFBMask[32];
9958     for (int i = 0; i < 32; ++i)
9959       PSHUFBMask[i] =
9960           Mask[i] < 0
9961               ? DAG.getUNDEF(MVT::i8)
9962               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9963                                 MVT::i8);
9964
9965     return DAG.getNode(
9966         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9967         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9968   }
9969
9970   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9971   // shuffle.
9972   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9973           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9974     return Result;
9975
9976   // Otherwise fall back on generic lowering.
9977   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9978 }
9979
9980 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9981 ///
9982 /// This routine either breaks down the specific type of a 256-bit x86 vector
9983 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9984 /// together based on the available instructions.
9985 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9986                                         MVT VT, const X86Subtarget *Subtarget,
9987                                         SelectionDAG &DAG) {
9988   SDLoc DL(Op);
9989   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9990   ArrayRef<int> Mask = SVOp->getMask();
9991
9992   // If we have a single input to the zero element, insert that into V1 if we
9993   // can do so cheaply.
9994   int NumElts = VT.getVectorNumElements();
9995   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9996     return M >= NumElts;
9997   });
9998
9999   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10000     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10001                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10002       return Insertion;
10003
10004   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10005   // check for those subtargets here and avoid much of the subtarget querying in
10006   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10007   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10008   // floating point types there eventually, just immediately cast everything to
10009   // a float and operate entirely in that domain.
10010   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10011     int ElementBits = VT.getScalarSizeInBits();
10012     if (ElementBits < 32)
10013       // No floating point type available, decompose into 128-bit vectors.
10014       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10015
10016     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10017                                 VT.getVectorNumElements());
10018     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10019     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10020     return DAG.getNode(ISD::BITCAST, DL, VT,
10021                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10022   }
10023
10024   switch (VT.SimpleTy) {
10025   case MVT::v4f64:
10026     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10027   case MVT::v4i64:
10028     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10029   case MVT::v8f32:
10030     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10031   case MVT::v8i32:
10032     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10033   case MVT::v16i16:
10034     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10035   case MVT::v32i8:
10036     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10037
10038   default:
10039     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10040   }
10041 }
10042
10043 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10044 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10045                                        const X86Subtarget *Subtarget,
10046                                        SelectionDAG &DAG) {
10047   SDLoc DL(Op);
10048   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10049   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10050   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10051   ArrayRef<int> Mask = SVOp->getMask();
10052   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10053
10054   // X86 has dedicated unpack instructions that can handle specific blend
10055   // operations: UNPCKH and UNPCKL.
10056   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10057     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10058   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10059     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10060
10061   // FIXME: Implement direct support for this type!
10062   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10063 }
10064
10065 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10066 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10067                                        const X86Subtarget *Subtarget,
10068                                        SelectionDAG &DAG) {
10069   SDLoc DL(Op);
10070   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10071   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10072   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10073   ArrayRef<int> Mask = SVOp->getMask();
10074   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10075
10076   // Use dedicated unpack instructions for masks that match their pattern.
10077   if (isShuffleEquivalent(V1, V2, Mask,
10078                           {// First 128-bit lane.
10079                            0, 16, 1, 17, 4, 20, 5, 21,
10080                            // Second 128-bit lane.
10081                            8, 24, 9, 25, 12, 28, 13, 29}))
10082     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10083   if (isShuffleEquivalent(V1, V2, Mask,
10084                           {// First 128-bit lane.
10085                            2, 18, 3, 19, 6, 22, 7, 23,
10086                            // Second 128-bit lane.
10087                            10, 26, 11, 27, 14, 30, 15, 31}))
10088     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10089
10090   // FIXME: Implement direct support for this type!
10091   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10092 }
10093
10094 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10095 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10096                                        const X86Subtarget *Subtarget,
10097                                        SelectionDAG &DAG) {
10098   SDLoc DL(Op);
10099   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10100   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10101   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10102   ArrayRef<int> Mask = SVOp->getMask();
10103   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10104
10105   // X86 has dedicated unpack instructions that can handle specific blend
10106   // operations: UNPCKH and UNPCKL.
10107   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10108     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10109   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10110     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10111
10112   // FIXME: Implement direct support for this type!
10113   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10114 }
10115
10116 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10117 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10118                                        const X86Subtarget *Subtarget,
10119                                        SelectionDAG &DAG) {
10120   SDLoc DL(Op);
10121   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10122   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10123   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10124   ArrayRef<int> Mask = SVOp->getMask();
10125   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10126
10127   // Use dedicated unpack instructions for masks that match their pattern.
10128   if (isShuffleEquivalent(V1, V2, Mask,
10129                           {// First 128-bit lane.
10130                            0, 16, 1, 17, 4, 20, 5, 21,
10131                            // Second 128-bit lane.
10132                            8, 24, 9, 25, 12, 28, 13, 29}))
10133     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10134   if (isShuffleEquivalent(V1, V2, Mask,
10135                           {// First 128-bit lane.
10136                            2, 18, 3, 19, 6, 22, 7, 23,
10137                            // Second 128-bit lane.
10138                            10, 26, 11, 27, 14, 30, 15, 31}))
10139     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10140
10141   // FIXME: Implement direct support for this type!
10142   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10143 }
10144
10145 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10146 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10147                                         const X86Subtarget *Subtarget,
10148                                         SelectionDAG &DAG) {
10149   SDLoc DL(Op);
10150   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10151   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10152   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10153   ArrayRef<int> Mask = SVOp->getMask();
10154   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10155   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10156
10157   // FIXME: Implement direct support for this type!
10158   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10159 }
10160
10161 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10162 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10163                                        const X86Subtarget *Subtarget,
10164                                        SelectionDAG &DAG) {
10165   SDLoc DL(Op);
10166   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10167   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10168   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10169   ArrayRef<int> Mask = SVOp->getMask();
10170   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10171   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10172
10173   // FIXME: Implement direct support for this type!
10174   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10175 }
10176
10177 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10178 ///
10179 /// This routine either breaks down the specific type of a 512-bit x86 vector
10180 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10181 /// together based on the available instructions.
10182 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10183                                         MVT VT, const X86Subtarget *Subtarget,
10184                                         SelectionDAG &DAG) {
10185   SDLoc DL(Op);
10186   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10187   ArrayRef<int> Mask = SVOp->getMask();
10188   assert(Subtarget->hasAVX512() &&
10189          "Cannot lower 512-bit vectors w/ basic ISA!");
10190
10191   // Check for being able to broadcast a single element.
10192   if (SDValue Broadcast =
10193           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10194     return Broadcast;
10195
10196   // Dispatch to each element type for lowering. If we don't have supprot for
10197   // specific element type shuffles at 512 bits, immediately split them and
10198   // lower them. Each lowering routine of a given type is allowed to assume that
10199   // the requisite ISA extensions for that element type are available.
10200   switch (VT.SimpleTy) {
10201   case MVT::v8f64:
10202     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10203   case MVT::v16f32:
10204     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10205   case MVT::v8i64:
10206     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10207   case MVT::v16i32:
10208     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10209   case MVT::v32i16:
10210     if (Subtarget->hasBWI())
10211       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10212     break;
10213   case MVT::v64i8:
10214     if (Subtarget->hasBWI())
10215       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10216     break;
10217
10218   default:
10219     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10220   }
10221
10222   // Otherwise fall back on splitting.
10223   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10224 }
10225
10226 /// \brief Top-level lowering for x86 vector shuffles.
10227 ///
10228 /// This handles decomposition, canonicalization, and lowering of all x86
10229 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10230 /// above in helper routines. The canonicalization attempts to widen shuffles
10231 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10232 /// s.t. only one of the two inputs needs to be tested, etc.
10233 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10234                                   SelectionDAG &DAG) {
10235   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10236   ArrayRef<int> Mask = SVOp->getMask();
10237   SDValue V1 = Op.getOperand(0);
10238   SDValue V2 = Op.getOperand(1);
10239   MVT VT = Op.getSimpleValueType();
10240   int NumElements = VT.getVectorNumElements();
10241   SDLoc dl(Op);
10242
10243   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10244
10245   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10246   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10247   if (V1IsUndef && V2IsUndef)
10248     return DAG.getUNDEF(VT);
10249
10250   // When we create a shuffle node we put the UNDEF node to second operand,
10251   // but in some cases the first operand may be transformed to UNDEF.
10252   // In this case we should just commute the node.
10253   if (V1IsUndef)
10254     return DAG.getCommutedVectorShuffle(*SVOp);
10255
10256   // Check for non-undef masks pointing at an undef vector and make the masks
10257   // undef as well. This makes it easier to match the shuffle based solely on
10258   // the mask.
10259   if (V2IsUndef)
10260     for (int M : Mask)
10261       if (M >= NumElements) {
10262         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10263         for (int &M : NewMask)
10264           if (M >= NumElements)
10265             M = -1;
10266         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10267       }
10268
10269   // We actually see shuffles that are entirely re-arrangements of a set of
10270   // zero inputs. This mostly happens while decomposing complex shuffles into
10271   // simple ones. Directly lower these as a buildvector of zeros.
10272   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10273   if (Zeroable.all())
10274     return getZeroVector(VT, Subtarget, DAG, dl);
10275
10276   // Try to collapse shuffles into using a vector type with fewer elements but
10277   // wider element types. We cap this to not form integers or floating point
10278   // elements wider than 64 bits, but it might be interesting to form i128
10279   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10280   SmallVector<int, 16> WidenedMask;
10281   if (VT.getScalarSizeInBits() < 64 &&
10282       canWidenShuffleElements(Mask, WidenedMask)) {
10283     MVT NewEltVT = VT.isFloatingPoint()
10284                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10285                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10286     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10287     // Make sure that the new vector type is legal. For example, v2f64 isn't
10288     // legal on SSE1.
10289     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10290       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10291       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10292       return DAG.getNode(ISD::BITCAST, dl, VT,
10293                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10294     }
10295   }
10296
10297   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10298   for (int M : SVOp->getMask())
10299     if (M < 0)
10300       ++NumUndefElements;
10301     else if (M < NumElements)
10302       ++NumV1Elements;
10303     else
10304       ++NumV2Elements;
10305
10306   // Commute the shuffle as needed such that more elements come from V1 than
10307   // V2. This allows us to match the shuffle pattern strictly on how many
10308   // elements come from V1 without handling the symmetric cases.
10309   if (NumV2Elements > NumV1Elements)
10310     return DAG.getCommutedVectorShuffle(*SVOp);
10311
10312   // When the number of V1 and V2 elements are the same, try to minimize the
10313   // number of uses of V2 in the low half of the vector. When that is tied,
10314   // ensure that the sum of indices for V1 is equal to or lower than the sum
10315   // indices for V2. When those are equal, try to ensure that the number of odd
10316   // indices for V1 is lower than the number of odd indices for V2.
10317   if (NumV1Elements == NumV2Elements) {
10318     int LowV1Elements = 0, LowV2Elements = 0;
10319     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10320       if (M >= NumElements)
10321         ++LowV2Elements;
10322       else if (M >= 0)
10323         ++LowV1Elements;
10324     if (LowV2Elements > LowV1Elements) {
10325       return DAG.getCommutedVectorShuffle(*SVOp);
10326     } else if (LowV2Elements == LowV1Elements) {
10327       int SumV1Indices = 0, SumV2Indices = 0;
10328       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10329         if (SVOp->getMask()[i] >= NumElements)
10330           SumV2Indices += i;
10331         else if (SVOp->getMask()[i] >= 0)
10332           SumV1Indices += i;
10333       if (SumV2Indices < SumV1Indices) {
10334         return DAG.getCommutedVectorShuffle(*SVOp);
10335       } else if (SumV2Indices == SumV1Indices) {
10336         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10337         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10338           if (SVOp->getMask()[i] >= NumElements)
10339             NumV2OddIndices += i % 2;
10340           else if (SVOp->getMask()[i] >= 0)
10341             NumV1OddIndices += i % 2;
10342         if (NumV2OddIndices < NumV1OddIndices)
10343           return DAG.getCommutedVectorShuffle(*SVOp);
10344       }
10345     }
10346   }
10347
10348   // For each vector width, delegate to a specialized lowering routine.
10349   if (VT.getSizeInBits() == 128)
10350     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10351
10352   if (VT.getSizeInBits() == 256)
10353     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10354
10355   // Force AVX-512 vectors to be scalarized for now.
10356   // FIXME: Implement AVX-512 support!
10357   if (VT.getSizeInBits() == 512)
10358     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10359
10360   llvm_unreachable("Unimplemented!");
10361 }
10362
10363 // This function assumes its argument is a BUILD_VECTOR of constants or
10364 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10365 // true.
10366 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10367                                     unsigned &MaskValue) {
10368   MaskValue = 0;
10369   unsigned NumElems = BuildVector->getNumOperands();
10370   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10371   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10372   unsigned NumElemsInLane = NumElems / NumLanes;
10373
10374   // Blend for v16i16 should be symetric for the both lanes.
10375   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10376     SDValue EltCond = BuildVector->getOperand(i);
10377     SDValue SndLaneEltCond =
10378         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10379
10380     int Lane1Cond = -1, Lane2Cond = -1;
10381     if (isa<ConstantSDNode>(EltCond))
10382       Lane1Cond = !isZero(EltCond);
10383     if (isa<ConstantSDNode>(SndLaneEltCond))
10384       Lane2Cond = !isZero(SndLaneEltCond);
10385
10386     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10387       // Lane1Cond != 0, means we want the first argument.
10388       // Lane1Cond == 0, means we want the second argument.
10389       // The encoding of this argument is 0 for the first argument, 1
10390       // for the second. Therefore, invert the condition.
10391       MaskValue |= !Lane1Cond << i;
10392     else if (Lane1Cond < 0)
10393       MaskValue |= !Lane2Cond << i;
10394     else
10395       return false;
10396   }
10397   return true;
10398 }
10399
10400 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10401 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10402                                            const X86Subtarget *Subtarget,
10403                                            SelectionDAG &DAG) {
10404   SDValue Cond = Op.getOperand(0);
10405   SDValue LHS = Op.getOperand(1);
10406   SDValue RHS = Op.getOperand(2);
10407   SDLoc dl(Op);
10408   MVT VT = Op.getSimpleValueType();
10409
10410   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10411     return SDValue();
10412   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10413
10414   // Only non-legal VSELECTs reach this lowering, convert those into generic
10415   // shuffles and re-use the shuffle lowering path for blends.
10416   SmallVector<int, 32> Mask;
10417   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10418     SDValue CondElt = CondBV->getOperand(i);
10419     Mask.push_back(
10420         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10421   }
10422   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10423 }
10424
10425 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10426   // A vselect where all conditions and data are constants can be optimized into
10427   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10428   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10429       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10430       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10431     return SDValue();
10432
10433   // Try to lower this to a blend-style vector shuffle. This can handle all
10434   // constant condition cases.
10435   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10436     return BlendOp;
10437
10438   // Variable blends are only legal from SSE4.1 onward.
10439   if (!Subtarget->hasSSE41())
10440     return SDValue();
10441
10442   // Only some types will be legal on some subtargets. If we can emit a legal
10443   // VSELECT-matching blend, return Op, and but if we need to expand, return
10444   // a null value.
10445   switch (Op.getSimpleValueType().SimpleTy) {
10446   default:
10447     // Most of the vector types have blends past SSE4.1.
10448     return Op;
10449
10450   case MVT::v32i8:
10451     // The byte blends for AVX vectors were introduced only in AVX2.
10452     if (Subtarget->hasAVX2())
10453       return Op;
10454
10455     return SDValue();
10456
10457   case MVT::v8i16:
10458   case MVT::v16i16:
10459     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10460     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10461       return Op;
10462
10463     // FIXME: We should custom lower this by fixing the condition and using i8
10464     // blends.
10465     return SDValue();
10466   }
10467 }
10468
10469 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10470   MVT VT = Op.getSimpleValueType();
10471   SDLoc dl(Op);
10472
10473   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10474     return SDValue();
10475
10476   if (VT.getSizeInBits() == 8) {
10477     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10478                                   Op.getOperand(0), Op.getOperand(1));
10479     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10480                                   DAG.getValueType(VT));
10481     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10482   }
10483
10484   if (VT.getSizeInBits() == 16) {
10485     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10486     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10487     if (Idx == 0)
10488       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10489                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10490                                      DAG.getNode(ISD::BITCAST, dl,
10491                                                  MVT::v4i32,
10492                                                  Op.getOperand(0)),
10493                                      Op.getOperand(1)));
10494     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10495                                   Op.getOperand(0), Op.getOperand(1));
10496     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10497                                   DAG.getValueType(VT));
10498     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10499   }
10500
10501   if (VT == MVT::f32) {
10502     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10503     // the result back to FR32 register. It's only worth matching if the
10504     // result has a single use which is a store or a bitcast to i32.  And in
10505     // the case of a store, it's not worth it if the index is a constant 0,
10506     // because a MOVSSmr can be used instead, which is smaller and faster.
10507     if (!Op.hasOneUse())
10508       return SDValue();
10509     SDNode *User = *Op.getNode()->use_begin();
10510     if ((User->getOpcode() != ISD::STORE ||
10511          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10512           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10513         (User->getOpcode() != ISD::BITCAST ||
10514          User->getValueType(0) != MVT::i32))
10515       return SDValue();
10516     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10517                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10518                                               Op.getOperand(0)),
10519                                               Op.getOperand(1));
10520     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10521   }
10522
10523   if (VT == MVT::i32 || VT == MVT::i64) {
10524     // ExtractPS/pextrq works with constant index.
10525     if (isa<ConstantSDNode>(Op.getOperand(1)))
10526       return Op;
10527   }
10528   return SDValue();
10529 }
10530
10531 /// Extract one bit from mask vector, like v16i1 or v8i1.
10532 /// AVX-512 feature.
10533 SDValue
10534 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10535   SDValue Vec = Op.getOperand(0);
10536   SDLoc dl(Vec);
10537   MVT VecVT = Vec.getSimpleValueType();
10538   SDValue Idx = Op.getOperand(1);
10539   MVT EltVT = Op.getSimpleValueType();
10540
10541   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10542   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10543          "Unexpected vector type in ExtractBitFromMaskVector");
10544
10545   // variable index can't be handled in mask registers,
10546   // extend vector to VR512
10547   if (!isa<ConstantSDNode>(Idx)) {
10548     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10549     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10550     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10551                               ExtVT.getVectorElementType(), Ext, Idx);
10552     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10553   }
10554
10555   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10556   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10557   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10558     rc = getRegClassFor(MVT::v16i1);
10559   unsigned MaxSift = rc->getSize()*8 - 1;
10560   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10561                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10562   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10563                     DAG.getConstant(MaxSift, dl, MVT::i8));
10564   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10565                        DAG.getIntPtrConstant(0, dl));
10566 }
10567
10568 SDValue
10569 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10570                                            SelectionDAG &DAG) const {
10571   SDLoc dl(Op);
10572   SDValue Vec = Op.getOperand(0);
10573   MVT VecVT = Vec.getSimpleValueType();
10574   SDValue Idx = Op.getOperand(1);
10575
10576   if (Op.getSimpleValueType() == MVT::i1)
10577     return ExtractBitFromMaskVector(Op, DAG);
10578
10579   if (!isa<ConstantSDNode>(Idx)) {
10580     if (VecVT.is512BitVector() ||
10581         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10582          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10583
10584       MVT MaskEltVT =
10585         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10586       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10587                                     MaskEltVT.getSizeInBits());
10588
10589       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10590       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10591                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10592                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10593       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10594       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10595                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10596     }
10597     return SDValue();
10598   }
10599
10600   // If this is a 256-bit vector result, first extract the 128-bit vector and
10601   // then extract the element from the 128-bit vector.
10602   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10603
10604     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10605     // Get the 128-bit vector.
10606     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10607     MVT EltVT = VecVT.getVectorElementType();
10608
10609     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10610
10611     //if (IdxVal >= NumElems/2)
10612     //  IdxVal -= NumElems/2;
10613     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10614     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10615                        DAG.getConstant(IdxVal, dl, MVT::i32));
10616   }
10617
10618   assert(VecVT.is128BitVector() && "Unexpected vector length");
10619
10620   if (Subtarget->hasSSE41()) {
10621     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10622     if (Res.getNode())
10623       return Res;
10624   }
10625
10626   MVT VT = Op.getSimpleValueType();
10627   // TODO: handle v16i8.
10628   if (VT.getSizeInBits() == 16) {
10629     SDValue Vec = Op.getOperand(0);
10630     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10631     if (Idx == 0)
10632       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10633                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10634                                      DAG.getNode(ISD::BITCAST, dl,
10635                                                  MVT::v4i32, Vec),
10636                                      Op.getOperand(1)));
10637     // Transform it so it match pextrw which produces a 32-bit result.
10638     MVT EltVT = MVT::i32;
10639     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10640                                   Op.getOperand(0), Op.getOperand(1));
10641     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10642                                   DAG.getValueType(VT));
10643     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10644   }
10645
10646   if (VT.getSizeInBits() == 32) {
10647     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10648     if (Idx == 0)
10649       return Op;
10650
10651     // SHUFPS the element to the lowest double word, then movss.
10652     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10653     MVT VVT = Op.getOperand(0).getSimpleValueType();
10654     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10655                                        DAG.getUNDEF(VVT), Mask);
10656     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10657                        DAG.getIntPtrConstant(0, dl));
10658   }
10659
10660   if (VT.getSizeInBits() == 64) {
10661     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10662     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10663     //        to match extract_elt for f64.
10664     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10665     if (Idx == 0)
10666       return Op;
10667
10668     // UNPCKHPD the element to the lowest double word, then movsd.
10669     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10670     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10671     int Mask[2] = { 1, -1 };
10672     MVT VVT = Op.getOperand(0).getSimpleValueType();
10673     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10674                                        DAG.getUNDEF(VVT), Mask);
10675     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10676                        DAG.getIntPtrConstant(0, dl));
10677   }
10678
10679   return SDValue();
10680 }
10681
10682 /// Insert one bit to mask vector, like v16i1 or v8i1.
10683 /// AVX-512 feature.
10684 SDValue
10685 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10686   SDLoc dl(Op);
10687   SDValue Vec = Op.getOperand(0);
10688   SDValue Elt = Op.getOperand(1);
10689   SDValue Idx = Op.getOperand(2);
10690   MVT VecVT = Vec.getSimpleValueType();
10691
10692   if (!isa<ConstantSDNode>(Idx)) {
10693     // Non constant index. Extend source and destination,
10694     // insert element and then truncate the result.
10695     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10696     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10697     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10698       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10699       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10700     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10701   }
10702
10703   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10704   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10705   if (IdxVal)
10706     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10707                            DAG.getConstant(IdxVal, dl, MVT::i8));
10708   if (Vec.getOpcode() == ISD::UNDEF)
10709     return EltInVec;
10710   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10711 }
10712
10713 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10714                                                   SelectionDAG &DAG) const {
10715   MVT VT = Op.getSimpleValueType();
10716   MVT EltVT = VT.getVectorElementType();
10717
10718   if (EltVT == MVT::i1)
10719     return InsertBitToMaskVector(Op, DAG);
10720
10721   SDLoc dl(Op);
10722   SDValue N0 = Op.getOperand(0);
10723   SDValue N1 = Op.getOperand(1);
10724   SDValue N2 = Op.getOperand(2);
10725   if (!isa<ConstantSDNode>(N2))
10726     return SDValue();
10727   auto *N2C = cast<ConstantSDNode>(N2);
10728   unsigned IdxVal = N2C->getZExtValue();
10729
10730   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10731   // into that, and then insert the subvector back into the result.
10732   if (VT.is256BitVector() || VT.is512BitVector()) {
10733     // With a 256-bit vector, we can insert into the zero element efficiently
10734     // using a blend if we have AVX or AVX2 and the right data type.
10735     if (VT.is256BitVector() && IdxVal == 0) {
10736       // TODO: It is worthwhile to cast integer to floating point and back
10737       // and incur a domain crossing penalty if that's what we'll end up
10738       // doing anyway after extracting to a 128-bit vector.
10739       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10740           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10741         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10742         N2 = DAG.getIntPtrConstant(1, dl);
10743         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10744       }
10745     }
10746
10747     // Get the desired 128-bit vector chunk.
10748     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10749
10750     // Insert the element into the desired chunk.
10751     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10752     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10753
10754     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10755                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10756
10757     // Insert the changed part back into the bigger vector
10758     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10759   }
10760   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10761
10762   if (Subtarget->hasSSE41()) {
10763     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10764       unsigned Opc;
10765       if (VT == MVT::v8i16) {
10766         Opc = X86ISD::PINSRW;
10767       } else {
10768         assert(VT == MVT::v16i8);
10769         Opc = X86ISD::PINSRB;
10770       }
10771
10772       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10773       // argument.
10774       if (N1.getValueType() != MVT::i32)
10775         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10776       if (N2.getValueType() != MVT::i32)
10777         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10778       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10779     }
10780
10781     if (EltVT == MVT::f32) {
10782       // Bits [7:6] of the constant are the source select. This will always be
10783       //   zero here. The DAG Combiner may combine an extract_elt index into
10784       //   these bits. For example (insert (extract, 3), 2) could be matched by
10785       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10786       // Bits [5:4] of the constant are the destination select. This is the
10787       //   value of the incoming immediate.
10788       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10789       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10790
10791       const Function *F = DAG.getMachineFunction().getFunction();
10792       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10793       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10794         // If this is an insertion of 32-bits into the low 32-bits of
10795         // a vector, we prefer to generate a blend with immediate rather
10796         // than an insertps. Blends are simpler operations in hardware and so
10797         // will always have equal or better performance than insertps.
10798         // But if optimizing for size and there's a load folding opportunity,
10799         // generate insertps because blendps does not have a 32-bit memory
10800         // operand form.
10801         N2 = DAG.getIntPtrConstant(1, dl);
10802         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10803         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10804       }
10805       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10806       // Create this as a scalar to vector..
10807       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10808       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10809     }
10810
10811     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10812       // PINSR* works with constant index.
10813       return Op;
10814     }
10815   }
10816
10817   if (EltVT == MVT::i8)
10818     return SDValue();
10819
10820   if (EltVT.getSizeInBits() == 16) {
10821     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10822     // as its second argument.
10823     if (N1.getValueType() != MVT::i32)
10824       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10825     if (N2.getValueType() != MVT::i32)
10826       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10827     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10828   }
10829   return SDValue();
10830 }
10831
10832 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10833   SDLoc dl(Op);
10834   MVT OpVT = Op.getSimpleValueType();
10835
10836   // If this is a 256-bit vector result, first insert into a 128-bit
10837   // vector and then insert into the 256-bit vector.
10838   if (!OpVT.is128BitVector()) {
10839     // Insert into a 128-bit vector.
10840     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10841     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10842                                  OpVT.getVectorNumElements() / SizeFactor);
10843
10844     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10845
10846     // Insert the 128-bit vector.
10847     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10848   }
10849
10850   if (OpVT == MVT::v1i64 &&
10851       Op.getOperand(0).getValueType() == MVT::i64)
10852     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10853
10854   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10855   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10856   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10857                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10858 }
10859
10860 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10861 // a simple subregister reference or explicit instructions to grab
10862 // upper bits of a vector.
10863 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10864                                       SelectionDAG &DAG) {
10865   SDLoc dl(Op);
10866   SDValue In =  Op.getOperand(0);
10867   SDValue Idx = Op.getOperand(1);
10868   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10869   MVT ResVT   = Op.getSimpleValueType();
10870   MVT InVT    = In.getSimpleValueType();
10871
10872   if (Subtarget->hasFp256()) {
10873     if (ResVT.is128BitVector() &&
10874         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10875         isa<ConstantSDNode>(Idx)) {
10876       return Extract128BitVector(In, IdxVal, DAG, dl);
10877     }
10878     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10879         isa<ConstantSDNode>(Idx)) {
10880       return Extract256BitVector(In, IdxVal, DAG, dl);
10881     }
10882   }
10883   return SDValue();
10884 }
10885
10886 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10887 // simple superregister reference or explicit instructions to insert
10888 // the upper bits of a vector.
10889 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10890                                      SelectionDAG &DAG) {
10891   if (!Subtarget->hasAVX())
10892     return SDValue();
10893
10894   SDLoc dl(Op);
10895   SDValue Vec = Op.getOperand(0);
10896   SDValue SubVec = Op.getOperand(1);
10897   SDValue Idx = Op.getOperand(2);
10898
10899   if (!isa<ConstantSDNode>(Idx))
10900     return SDValue();
10901
10902   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10903   MVT OpVT = Op.getSimpleValueType();
10904   MVT SubVecVT = SubVec.getSimpleValueType();
10905
10906   // Fold two 16-byte subvector loads into one 32-byte load:
10907   // (insert_subvector (insert_subvector undef, (load addr), 0),
10908   //                   (load addr + 16), Elts/2)
10909   // --> load32 addr
10910   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10911       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10912       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10913       !Subtarget->isUnalignedMem32Slow()) {
10914     SDValue SubVec2 = Vec.getOperand(1);
10915     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10916       if (Idx2->getZExtValue() == 0) {
10917         SDValue Ops[] = { SubVec2, SubVec };
10918         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10919         if (LD.getNode())
10920           return LD;
10921       }
10922     }
10923   }
10924
10925   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10926       SubVecVT.is128BitVector())
10927     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10928
10929   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10930     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10931
10932   if (OpVT.getVectorElementType() == MVT::i1) {
10933     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10934       return Op;
10935     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10936     SDValue Undef = DAG.getUNDEF(OpVT);
10937     unsigned NumElems = OpVT.getVectorNumElements();
10938     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10939
10940     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10941       // Zero upper bits of the Vec
10942       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10943       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10944
10945       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10946                                  SubVec, ZeroIdx);
10947       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10948       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10949     }
10950     if (IdxVal == 0) {
10951       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10952                                  SubVec, ZeroIdx);
10953       // Zero upper bits of the Vec2
10954       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10955       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10956       // Zero lower bits of the Vec
10957       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10958       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10959       // Merge them together
10960       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10961     }
10962   }
10963   return SDValue();
10964 }
10965
10966 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10967 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10968 // one of the above mentioned nodes. It has to be wrapped because otherwise
10969 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10970 // be used to form addressing mode. These wrapped nodes will be selected
10971 // into MOV32ri.
10972 SDValue
10973 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10974   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10975
10976   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10977   // global base reg.
10978   unsigned char OpFlag = 0;
10979   unsigned WrapperKind = X86ISD::Wrapper;
10980   CodeModel::Model M = DAG.getTarget().getCodeModel();
10981
10982   if (Subtarget->isPICStyleRIPRel() &&
10983       (M == CodeModel::Small || M == CodeModel::Kernel))
10984     WrapperKind = X86ISD::WrapperRIP;
10985   else if (Subtarget->isPICStyleGOT())
10986     OpFlag = X86II::MO_GOTOFF;
10987   else if (Subtarget->isPICStyleStubPIC())
10988     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10989
10990   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10991                                              CP->getAlignment(),
10992                                              CP->getOffset(), OpFlag);
10993   SDLoc DL(CP);
10994   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10995   // With PIC, the address is actually $g + Offset.
10996   if (OpFlag) {
10997     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10998                          DAG.getNode(X86ISD::GlobalBaseReg,
10999                                      SDLoc(), getPointerTy()),
11000                          Result);
11001   }
11002
11003   return Result;
11004 }
11005
11006 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11007   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11008
11009   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11010   // global base reg.
11011   unsigned char OpFlag = 0;
11012   unsigned WrapperKind = X86ISD::Wrapper;
11013   CodeModel::Model M = DAG.getTarget().getCodeModel();
11014
11015   if (Subtarget->isPICStyleRIPRel() &&
11016       (M == CodeModel::Small || M == CodeModel::Kernel))
11017     WrapperKind = X86ISD::WrapperRIP;
11018   else if (Subtarget->isPICStyleGOT())
11019     OpFlag = X86II::MO_GOTOFF;
11020   else if (Subtarget->isPICStyleStubPIC())
11021     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11022
11023   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11024                                           OpFlag);
11025   SDLoc DL(JT);
11026   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11027
11028   // With PIC, the address is actually $g + Offset.
11029   if (OpFlag)
11030     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11031                          DAG.getNode(X86ISD::GlobalBaseReg,
11032                                      SDLoc(), getPointerTy()),
11033                          Result);
11034
11035   return Result;
11036 }
11037
11038 SDValue
11039 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11040   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11041
11042   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11043   // global base reg.
11044   unsigned char OpFlag = 0;
11045   unsigned WrapperKind = X86ISD::Wrapper;
11046   CodeModel::Model M = DAG.getTarget().getCodeModel();
11047
11048   if (Subtarget->isPICStyleRIPRel() &&
11049       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11050     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11051       OpFlag = X86II::MO_GOTPCREL;
11052     WrapperKind = X86ISD::WrapperRIP;
11053   } else if (Subtarget->isPICStyleGOT()) {
11054     OpFlag = X86II::MO_GOT;
11055   } else if (Subtarget->isPICStyleStubPIC()) {
11056     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11057   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11058     OpFlag = X86II::MO_DARWIN_NONLAZY;
11059   }
11060
11061   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11062
11063   SDLoc DL(Op);
11064   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11065
11066   // With PIC, the address is actually $g + Offset.
11067   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11068       !Subtarget->is64Bit()) {
11069     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11070                          DAG.getNode(X86ISD::GlobalBaseReg,
11071                                      SDLoc(), getPointerTy()),
11072                          Result);
11073   }
11074
11075   // For symbols that require a load from a stub to get the address, emit the
11076   // load.
11077   if (isGlobalStubReference(OpFlag))
11078     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11079                          MachinePointerInfo::getGOT(), false, false, false, 0);
11080
11081   return Result;
11082 }
11083
11084 SDValue
11085 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11086   // Create the TargetBlockAddressAddress node.
11087   unsigned char OpFlags =
11088     Subtarget->ClassifyBlockAddressReference();
11089   CodeModel::Model M = DAG.getTarget().getCodeModel();
11090   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11091   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11092   SDLoc dl(Op);
11093   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11094                                              OpFlags);
11095
11096   if (Subtarget->isPICStyleRIPRel() &&
11097       (M == CodeModel::Small || M == CodeModel::Kernel))
11098     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11099   else
11100     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11101
11102   // With PIC, the address is actually $g + Offset.
11103   if (isGlobalRelativeToPICBase(OpFlags)) {
11104     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11105                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11106                          Result);
11107   }
11108
11109   return Result;
11110 }
11111
11112 SDValue
11113 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11114                                       int64_t Offset, SelectionDAG &DAG) const {
11115   // Create the TargetGlobalAddress node, folding in the constant
11116   // offset if it is legal.
11117   unsigned char OpFlags =
11118       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11119   CodeModel::Model M = DAG.getTarget().getCodeModel();
11120   SDValue Result;
11121   if (OpFlags == X86II::MO_NO_FLAG &&
11122       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11123     // A direct static reference to a global.
11124     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11125     Offset = 0;
11126   } else {
11127     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11128   }
11129
11130   if (Subtarget->isPICStyleRIPRel() &&
11131       (M == CodeModel::Small || M == CodeModel::Kernel))
11132     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11133   else
11134     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11135
11136   // With PIC, the address is actually $g + Offset.
11137   if (isGlobalRelativeToPICBase(OpFlags)) {
11138     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11139                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11140                          Result);
11141   }
11142
11143   // For globals that require a load from a stub to get the address, emit the
11144   // load.
11145   if (isGlobalStubReference(OpFlags))
11146     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11147                          MachinePointerInfo::getGOT(), false, false, false, 0);
11148
11149   // If there was a non-zero offset that we didn't fold, create an explicit
11150   // addition for it.
11151   if (Offset != 0)
11152     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11153                          DAG.getConstant(Offset, dl, getPointerTy()));
11154
11155   return Result;
11156 }
11157
11158 SDValue
11159 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11160   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11161   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11162   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11163 }
11164
11165 static SDValue
11166 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11167            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11168            unsigned char OperandFlags, bool LocalDynamic = false) {
11169   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11170   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11171   SDLoc dl(GA);
11172   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11173                                            GA->getValueType(0),
11174                                            GA->getOffset(),
11175                                            OperandFlags);
11176
11177   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11178                                            : X86ISD::TLSADDR;
11179
11180   if (InFlag) {
11181     SDValue Ops[] = { Chain,  TGA, *InFlag };
11182     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11183   } else {
11184     SDValue Ops[]  = { Chain, TGA };
11185     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11186   }
11187
11188   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11189   MFI->setAdjustsStack(true);
11190   MFI->setHasCalls(true);
11191
11192   SDValue Flag = Chain.getValue(1);
11193   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11194 }
11195
11196 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11197 static SDValue
11198 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11199                                 const EVT PtrVT) {
11200   SDValue InFlag;
11201   SDLoc dl(GA);  // ? function entry point might be better
11202   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11203                                    DAG.getNode(X86ISD::GlobalBaseReg,
11204                                                SDLoc(), PtrVT), InFlag);
11205   InFlag = Chain.getValue(1);
11206
11207   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11208 }
11209
11210 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11211 static SDValue
11212 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11213                                 const EVT PtrVT) {
11214   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11215                     X86::RAX, X86II::MO_TLSGD);
11216 }
11217
11218 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11219                                            SelectionDAG &DAG,
11220                                            const EVT PtrVT,
11221                                            bool is64Bit) {
11222   SDLoc dl(GA);
11223
11224   // Get the start address of the TLS block for this module.
11225   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11226       .getInfo<X86MachineFunctionInfo>();
11227   MFI->incNumLocalDynamicTLSAccesses();
11228
11229   SDValue Base;
11230   if (is64Bit) {
11231     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11232                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11233   } else {
11234     SDValue InFlag;
11235     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11236         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11237     InFlag = Chain.getValue(1);
11238     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11239                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11240   }
11241
11242   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11243   // of Base.
11244
11245   // Build x@dtpoff.
11246   unsigned char OperandFlags = X86II::MO_DTPOFF;
11247   unsigned WrapperKind = X86ISD::Wrapper;
11248   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11249                                            GA->getValueType(0),
11250                                            GA->getOffset(), OperandFlags);
11251   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11252
11253   // Add x@dtpoff with the base.
11254   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11255 }
11256
11257 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11258 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11259                                    const EVT PtrVT, TLSModel::Model model,
11260                                    bool is64Bit, bool isPIC) {
11261   SDLoc dl(GA);
11262
11263   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11264   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11265                                                          is64Bit ? 257 : 256));
11266
11267   SDValue ThreadPointer =
11268       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11269                   MachinePointerInfo(Ptr), false, false, false, 0);
11270
11271   unsigned char OperandFlags = 0;
11272   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11273   // initialexec.
11274   unsigned WrapperKind = X86ISD::Wrapper;
11275   if (model == TLSModel::LocalExec) {
11276     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11277   } else if (model == TLSModel::InitialExec) {
11278     if (is64Bit) {
11279       OperandFlags = X86II::MO_GOTTPOFF;
11280       WrapperKind = X86ISD::WrapperRIP;
11281     } else {
11282       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11283     }
11284   } else {
11285     llvm_unreachable("Unexpected model");
11286   }
11287
11288   // emit "addl x@ntpoff,%eax" (local exec)
11289   // or "addl x@indntpoff,%eax" (initial exec)
11290   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11291   SDValue TGA =
11292       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11293                                  GA->getOffset(), OperandFlags);
11294   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11295
11296   if (model == TLSModel::InitialExec) {
11297     if (isPIC && !is64Bit) {
11298       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11299                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11300                            Offset);
11301     }
11302
11303     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11304                          MachinePointerInfo::getGOT(), false, false, false, 0);
11305   }
11306
11307   // The address of the thread local variable is the add of the thread
11308   // pointer with the offset of the variable.
11309   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11310 }
11311
11312 SDValue
11313 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11314
11315   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11316   const GlobalValue *GV = GA->getGlobal();
11317
11318   if (Subtarget->isTargetELF()) {
11319     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11320     switch (model) {
11321       case TLSModel::GeneralDynamic:
11322         if (Subtarget->is64Bit())
11323           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11324         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11325       case TLSModel::LocalDynamic:
11326         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11327                                            Subtarget->is64Bit());
11328       case TLSModel::InitialExec:
11329       case TLSModel::LocalExec:
11330         return LowerToTLSExecModel(
11331             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11332             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11333     }
11334     llvm_unreachable("Unknown TLS model.");
11335   }
11336
11337   if (Subtarget->isTargetDarwin()) {
11338     // Darwin only has one model of TLS.  Lower to that.
11339     unsigned char OpFlag = 0;
11340     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11341                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11342
11343     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11344     // global base reg.
11345     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11346                  !Subtarget->is64Bit();
11347     if (PIC32)
11348       OpFlag = X86II::MO_TLVP_PIC_BASE;
11349     else
11350       OpFlag = X86II::MO_TLVP;
11351     SDLoc DL(Op);
11352     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11353                                                 GA->getValueType(0),
11354                                                 GA->getOffset(), OpFlag);
11355     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11356
11357     // With PIC32, the address is actually $g + Offset.
11358     if (PIC32)
11359       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11360                            DAG.getNode(X86ISD::GlobalBaseReg,
11361                                        SDLoc(), getPointerTy()),
11362                            Offset);
11363
11364     // Lowering the machine isd will make sure everything is in the right
11365     // location.
11366     SDValue Chain = DAG.getEntryNode();
11367     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11368     SDValue Args[] = { Chain, Offset };
11369     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11370
11371     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11372     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11373     MFI->setAdjustsStack(true);
11374
11375     // And our return value (tls address) is in the standard call return value
11376     // location.
11377     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11378     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11379                               Chain.getValue(1));
11380   }
11381
11382   if (Subtarget->isTargetKnownWindowsMSVC() ||
11383       Subtarget->isTargetWindowsGNU()) {
11384     // Just use the implicit TLS architecture
11385     // Need to generate someting similar to:
11386     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11387     //                                  ; from TEB
11388     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11389     //   mov     rcx, qword [rdx+rcx*8]
11390     //   mov     eax, .tls$:tlsvar
11391     //   [rax+rcx] contains the address
11392     // Windows 64bit: gs:0x58
11393     // Windows 32bit: fs:__tls_array
11394
11395     SDLoc dl(GA);
11396     SDValue Chain = DAG.getEntryNode();
11397
11398     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11399     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11400     // use its literal value of 0x2C.
11401     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11402                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11403                                                              256)
11404                                         : Type::getInt32PtrTy(*DAG.getContext(),
11405                                                               257));
11406
11407     SDValue TlsArray =
11408         Subtarget->is64Bit()
11409             ? DAG.getIntPtrConstant(0x58, dl)
11410             : (Subtarget->isTargetWindowsGNU()
11411                    ? DAG.getIntPtrConstant(0x2C, dl)
11412                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11413
11414     SDValue ThreadPointer =
11415         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11416                     MachinePointerInfo(Ptr), false, false, false, 0);
11417
11418     SDValue res;
11419     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11420       res = ThreadPointer;
11421     } else {
11422       // Load the _tls_index variable
11423       SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11424       if (Subtarget->is64Bit())
11425         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11426                              MachinePointerInfo(), MVT::i32, false, false,
11427                              false, 0);
11428       else
11429         IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11430                           false, false, false, 0);
11431
11432       SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11433                                       getPointerTy());
11434       IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11435
11436       res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11437     }
11438
11439     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11440                       false, false, false, 0);
11441
11442     // Get the offset of start of .tls section
11443     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11444                                              GA->getValueType(0),
11445                                              GA->getOffset(), X86II::MO_SECREL);
11446     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11447
11448     // The address of the thread local variable is the add of the thread
11449     // pointer with the offset of the variable.
11450     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11451   }
11452
11453   llvm_unreachable("TLS not implemented for this target.");
11454 }
11455
11456 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11457 /// and take a 2 x i32 value to shift plus a shift amount.
11458 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11459   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11460   MVT VT = Op.getSimpleValueType();
11461   unsigned VTBits = VT.getSizeInBits();
11462   SDLoc dl(Op);
11463   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11464   SDValue ShOpLo = Op.getOperand(0);
11465   SDValue ShOpHi = Op.getOperand(1);
11466   SDValue ShAmt  = Op.getOperand(2);
11467   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11468   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11469   // during isel.
11470   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11471                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11472   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11473                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11474                        : DAG.getConstant(0, dl, VT);
11475
11476   SDValue Tmp2, Tmp3;
11477   if (Op.getOpcode() == ISD::SHL_PARTS) {
11478     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11479     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11480   } else {
11481     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11482     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11483   }
11484
11485   // If the shift amount is larger or equal than the width of a part we can't
11486   // rely on the results of shld/shrd. Insert a test and select the appropriate
11487   // values for large shift amounts.
11488   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11489                                 DAG.getConstant(VTBits, dl, MVT::i8));
11490   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11491                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11492
11493   SDValue Hi, Lo;
11494   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11495   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11496   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11497
11498   if (Op.getOpcode() == ISD::SHL_PARTS) {
11499     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11500     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11501   } else {
11502     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11503     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11504   }
11505
11506   SDValue Ops[2] = { Lo, Hi };
11507   return DAG.getMergeValues(Ops, dl);
11508 }
11509
11510 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11511                                            SelectionDAG &DAG) const {
11512   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11513   SDLoc dl(Op);
11514
11515   if (SrcVT.isVector()) {
11516     if (SrcVT.getVectorElementType() == MVT::i1) {
11517       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11518       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11519                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11520                                      Op.getOperand(0)));
11521     }
11522     return SDValue();
11523   }
11524
11525   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11526          "Unknown SINT_TO_FP to lower!");
11527
11528   // These are really Legal; return the operand so the caller accepts it as
11529   // Legal.
11530   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11531     return Op;
11532   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11533       Subtarget->is64Bit()) {
11534     return Op;
11535   }
11536
11537   unsigned Size = SrcVT.getSizeInBits()/8;
11538   MachineFunction &MF = DAG.getMachineFunction();
11539   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11540   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11541   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11542                                StackSlot,
11543                                MachinePointerInfo::getFixedStack(SSFI),
11544                                false, false, 0);
11545   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11546 }
11547
11548 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11549                                      SDValue StackSlot,
11550                                      SelectionDAG &DAG) const {
11551   // Build the FILD
11552   SDLoc DL(Op);
11553   SDVTList Tys;
11554   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11555   if (useSSE)
11556     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11557   else
11558     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11559
11560   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11561
11562   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11563   MachineMemOperand *MMO;
11564   if (FI) {
11565     int SSFI = FI->getIndex();
11566     MMO =
11567       DAG.getMachineFunction()
11568       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11569                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11570   } else {
11571     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11572     StackSlot = StackSlot.getOperand(1);
11573   }
11574   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11575   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11576                                            X86ISD::FILD, DL,
11577                                            Tys, Ops, SrcVT, MMO);
11578
11579   if (useSSE) {
11580     Chain = Result.getValue(1);
11581     SDValue InFlag = Result.getValue(2);
11582
11583     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11584     // shouldn't be necessary except that RFP cannot be live across
11585     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11586     MachineFunction &MF = DAG.getMachineFunction();
11587     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11588     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11589     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11590     Tys = DAG.getVTList(MVT::Other);
11591     SDValue Ops[] = {
11592       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11593     };
11594     MachineMemOperand *MMO =
11595       DAG.getMachineFunction()
11596       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11597                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11598
11599     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11600                                     Ops, Op.getValueType(), MMO);
11601     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11602                          MachinePointerInfo::getFixedStack(SSFI),
11603                          false, false, false, 0);
11604   }
11605
11606   return Result;
11607 }
11608
11609 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11610 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11611                                                SelectionDAG &DAG) const {
11612   // This algorithm is not obvious. Here it is what we're trying to output:
11613   /*
11614      movq       %rax,  %xmm0
11615      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11616      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11617      #ifdef __SSE3__
11618        haddpd   %xmm0, %xmm0
11619      #else
11620        pshufd   $0x4e, %xmm0, %xmm1
11621        addpd    %xmm1, %xmm0
11622      #endif
11623   */
11624
11625   SDLoc dl(Op);
11626   LLVMContext *Context = DAG.getContext();
11627
11628   // Build some magic constants.
11629   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11630   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11631   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11632
11633   SmallVector<Constant*,2> CV1;
11634   CV1.push_back(
11635     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11636                                       APInt(64, 0x4330000000000000ULL))));
11637   CV1.push_back(
11638     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11639                                       APInt(64, 0x4530000000000000ULL))));
11640   Constant *C1 = ConstantVector::get(CV1);
11641   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11642
11643   // Load the 64-bit value into an XMM register.
11644   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11645                             Op.getOperand(0));
11646   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11647                               MachinePointerInfo::getConstantPool(),
11648                               false, false, false, 16);
11649   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11650                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11651                               CLod0);
11652
11653   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11654                               MachinePointerInfo::getConstantPool(),
11655                               false, false, false, 16);
11656   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11657   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11658   SDValue Result;
11659
11660   if (Subtarget->hasSSE3()) {
11661     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11662     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11663   } else {
11664     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11665     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11666                                            S2F, 0x4E, DAG);
11667     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11668                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11669                          Sub);
11670   }
11671
11672   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11673                      DAG.getIntPtrConstant(0, dl));
11674 }
11675
11676 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11677 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11678                                                SelectionDAG &DAG) const {
11679   SDLoc dl(Op);
11680   // FP constant to bias correct the final result.
11681   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11682                                    MVT::f64);
11683
11684   // Load the 32-bit value into an XMM register.
11685   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11686                              Op.getOperand(0));
11687
11688   // Zero out the upper parts of the register.
11689   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11690
11691   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11692                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11693                      DAG.getIntPtrConstant(0, dl));
11694
11695   // Or the load with the bias.
11696   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11697                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11698                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11699                                                    MVT::v2f64, Load)),
11700                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11701                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11702                                                    MVT::v2f64, Bias)));
11703   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11704                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11705                    DAG.getIntPtrConstant(0, dl));
11706
11707   // Subtract the bias.
11708   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11709
11710   // Handle final rounding.
11711   EVT DestVT = Op.getValueType();
11712
11713   if (DestVT.bitsLT(MVT::f64))
11714     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11715                        DAG.getIntPtrConstant(0, dl));
11716   if (DestVT.bitsGT(MVT::f64))
11717     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11718
11719   // Handle final rounding.
11720   return Sub;
11721 }
11722
11723 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11724                                      const X86Subtarget &Subtarget) {
11725   // The algorithm is the following:
11726   // #ifdef __SSE4_1__
11727   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11728   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11729   //                                 (uint4) 0x53000000, 0xaa);
11730   // #else
11731   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11732   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11733   // #endif
11734   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11735   //     return (float4) lo + fhi;
11736
11737   SDLoc DL(Op);
11738   SDValue V = Op->getOperand(0);
11739   EVT VecIntVT = V.getValueType();
11740   bool Is128 = VecIntVT == MVT::v4i32;
11741   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11742   // If we convert to something else than the supported type, e.g., to v4f64,
11743   // abort early.
11744   if (VecFloatVT != Op->getValueType(0))
11745     return SDValue();
11746
11747   unsigned NumElts = VecIntVT.getVectorNumElements();
11748   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11749          "Unsupported custom type");
11750   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11751
11752   // In the #idef/#else code, we have in common:
11753   // - The vector of constants:
11754   // -- 0x4b000000
11755   // -- 0x53000000
11756   // - A shift:
11757   // -- v >> 16
11758
11759   // Create the splat vector for 0x4b000000.
11760   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11761   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11762                            CstLow, CstLow, CstLow, CstLow};
11763   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11764                                   makeArrayRef(&CstLowArray[0], NumElts));
11765   // Create the splat vector for 0x53000000.
11766   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11767   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11768                             CstHigh, CstHigh, CstHigh, CstHigh};
11769   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11770                                    makeArrayRef(&CstHighArray[0], NumElts));
11771
11772   // Create the right shift.
11773   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11774   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11775                              CstShift, CstShift, CstShift, CstShift};
11776   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11777                                     makeArrayRef(&CstShiftArray[0], NumElts));
11778   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11779
11780   SDValue Low, High;
11781   if (Subtarget.hasSSE41()) {
11782     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11783     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11784     SDValue VecCstLowBitcast =
11785         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11786     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11787     // Low will be bitcasted right away, so do not bother bitcasting back to its
11788     // original type.
11789     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11790                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11791     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11792     //                                 (uint4) 0x53000000, 0xaa);
11793     SDValue VecCstHighBitcast =
11794         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11795     SDValue VecShiftBitcast =
11796         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11797     // High will be bitcasted right away, so do not bother bitcasting back to
11798     // its original type.
11799     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11800                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11801   } else {
11802     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11803     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11804                                      CstMask, CstMask, CstMask);
11805     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11806     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11807     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11808
11809     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11810     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11811   }
11812
11813   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11814   SDValue CstFAdd = DAG.getConstantFP(
11815       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11816   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11817                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11818   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11819                                    makeArrayRef(&CstFAddArray[0], NumElts));
11820
11821   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11822   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11823   SDValue FHigh =
11824       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11825   //     return (float4) lo + fhi;
11826   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11827   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11828 }
11829
11830 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11831                                                SelectionDAG &DAG) const {
11832   SDValue N0 = Op.getOperand(0);
11833   MVT SVT = N0.getSimpleValueType();
11834   SDLoc dl(Op);
11835
11836   switch (SVT.SimpleTy) {
11837   default:
11838     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11839   case MVT::v4i8:
11840   case MVT::v4i16:
11841   case MVT::v8i8:
11842   case MVT::v8i16: {
11843     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11844     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11845                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11846   }
11847   case MVT::v4i32:
11848   case MVT::v8i32:
11849     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11850   case MVT::v16i8:
11851   case MVT::v16i16:
11852     if (Subtarget->hasAVX512())
11853       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11854                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11855   }
11856   llvm_unreachable(nullptr);
11857 }
11858
11859 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11860                                            SelectionDAG &DAG) const {
11861   SDValue N0 = Op.getOperand(0);
11862   SDLoc dl(Op);
11863
11864   if (Op.getValueType().isVector())
11865     return lowerUINT_TO_FP_vec(Op, DAG);
11866
11867   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11868   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11869   // the optimization here.
11870   if (DAG.SignBitIsZero(N0))
11871     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11872
11873   MVT SrcVT = N0.getSimpleValueType();
11874   MVT DstVT = Op.getSimpleValueType();
11875   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11876     return LowerUINT_TO_FP_i64(Op, DAG);
11877   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11878     return LowerUINT_TO_FP_i32(Op, DAG);
11879   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11880     return SDValue();
11881
11882   // Make a 64-bit buffer, and use it to build an FILD.
11883   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11884   if (SrcVT == MVT::i32) {
11885     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11886     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11887                                      getPointerTy(), StackSlot, WordOff);
11888     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11889                                   StackSlot, MachinePointerInfo(),
11890                                   false, false, 0);
11891     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11892                                   OffsetSlot, MachinePointerInfo(),
11893                                   false, false, 0);
11894     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11895     return Fild;
11896   }
11897
11898   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11899   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11900                                StackSlot, MachinePointerInfo(),
11901                                false, false, 0);
11902   // For i64 source, we need to add the appropriate power of 2 if the input
11903   // was negative.  This is the same as the optimization in
11904   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11905   // we must be careful to do the computation in x87 extended precision, not
11906   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11907   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11908   MachineMemOperand *MMO =
11909     DAG.getMachineFunction()
11910     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11911                           MachineMemOperand::MOLoad, 8, 8);
11912
11913   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11914   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11915   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11916                                          MVT::i64, MMO);
11917
11918   APInt FF(32, 0x5F800000ULL);
11919
11920   // Check whether the sign bit is set.
11921   SDValue SignSet = DAG.getSetCC(dl,
11922                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11923                                  Op.getOperand(0),
11924                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11925
11926   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11927   SDValue FudgePtr = DAG.getConstantPool(
11928                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11929                                          getPointerTy());
11930
11931   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11932   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11933   SDValue Four = DAG.getIntPtrConstant(4, dl);
11934   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11935                                Zero, Four);
11936   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11937
11938   // Load the value out, extending it from f32 to f80.
11939   // FIXME: Avoid the extend by constructing the right constant pool?
11940   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11941                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11942                                  MVT::f32, false, false, false, 4);
11943   // Extend everything to 80 bits to force it to be done on x87.
11944   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11945   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11946                      DAG.getIntPtrConstant(0, dl));
11947 }
11948
11949 std::pair<SDValue,SDValue>
11950 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11951                                     bool IsSigned, bool IsReplace) const {
11952   SDLoc DL(Op);
11953
11954   EVT DstTy = Op.getValueType();
11955
11956   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11957     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11958     DstTy = MVT::i64;
11959   }
11960
11961   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11962          DstTy.getSimpleVT() >= MVT::i16 &&
11963          "Unknown FP_TO_INT to lower!");
11964
11965   // These are really Legal.
11966   if (DstTy == MVT::i32 &&
11967       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11968     return std::make_pair(SDValue(), SDValue());
11969   if (Subtarget->is64Bit() &&
11970       DstTy == MVT::i64 &&
11971       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11972     return std::make_pair(SDValue(), SDValue());
11973
11974   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11975   // stack slot, or into the FTOL runtime function.
11976   MachineFunction &MF = DAG.getMachineFunction();
11977   unsigned MemSize = DstTy.getSizeInBits()/8;
11978   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11979   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11980
11981   unsigned Opc;
11982   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11983     Opc = X86ISD::WIN_FTOL;
11984   else
11985     switch (DstTy.getSimpleVT().SimpleTy) {
11986     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11987     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11988     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11989     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11990     }
11991
11992   SDValue Chain = DAG.getEntryNode();
11993   SDValue Value = Op.getOperand(0);
11994   EVT TheVT = Op.getOperand(0).getValueType();
11995   // FIXME This causes a redundant load/store if the SSE-class value is already
11996   // in memory, such as if it is on the callstack.
11997   if (isScalarFPTypeInSSEReg(TheVT)) {
11998     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11999     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12000                          MachinePointerInfo::getFixedStack(SSFI),
12001                          false, false, 0);
12002     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12003     SDValue Ops[] = {
12004       Chain, StackSlot, DAG.getValueType(TheVT)
12005     };
12006
12007     MachineMemOperand *MMO =
12008       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12009                               MachineMemOperand::MOLoad, MemSize, MemSize);
12010     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12011     Chain = Value.getValue(1);
12012     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12013     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12014   }
12015
12016   MachineMemOperand *MMO =
12017     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12018                             MachineMemOperand::MOStore, MemSize, MemSize);
12019
12020   if (Opc != X86ISD::WIN_FTOL) {
12021     // Build the FP_TO_INT*_IN_MEM
12022     SDValue Ops[] = { Chain, Value, StackSlot };
12023     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12024                                            Ops, DstTy, MMO);
12025     return std::make_pair(FIST, StackSlot);
12026   } else {
12027     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12028       DAG.getVTList(MVT::Other, MVT::Glue),
12029       Chain, Value);
12030     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12031       MVT::i32, ftol.getValue(1));
12032     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12033       MVT::i32, eax.getValue(2));
12034     SDValue Ops[] = { eax, edx };
12035     SDValue pair = IsReplace
12036       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12037       : DAG.getMergeValues(Ops, DL);
12038     return std::make_pair(pair, SDValue());
12039   }
12040 }
12041
12042 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12043                               const X86Subtarget *Subtarget) {
12044   MVT VT = Op->getSimpleValueType(0);
12045   SDValue In = Op->getOperand(0);
12046   MVT InVT = In.getSimpleValueType();
12047   SDLoc dl(Op);
12048
12049   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12050     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12051
12052   // Optimize vectors in AVX mode:
12053   //
12054   //   v8i16 -> v8i32
12055   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12056   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12057   //   Concat upper and lower parts.
12058   //
12059   //   v4i32 -> v4i64
12060   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12061   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12062   //   Concat upper and lower parts.
12063   //
12064
12065   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12066       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12067       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12068     return SDValue();
12069
12070   if (Subtarget->hasInt256())
12071     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12072
12073   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12074   SDValue Undef = DAG.getUNDEF(InVT);
12075   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12076   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12077   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12078
12079   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12080                              VT.getVectorNumElements()/2);
12081
12082   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12083   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12084
12085   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12086 }
12087
12088 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12089                                         SelectionDAG &DAG) {
12090   MVT VT = Op->getSimpleValueType(0);
12091   SDValue In = Op->getOperand(0);
12092   MVT InVT = In.getSimpleValueType();
12093   SDLoc DL(Op);
12094   unsigned int NumElts = VT.getVectorNumElements();
12095   if (NumElts != 8 && NumElts != 16)
12096     return SDValue();
12097
12098   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12099     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12100
12101   assert(InVT.getVectorElementType() == MVT::i1);
12102   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12103   SDValue One =
12104    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12105   SDValue Zero =
12106    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12107
12108   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12109   if (VT.is512BitVector())
12110     return V;
12111   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12112 }
12113
12114 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12115                                SelectionDAG &DAG) {
12116   if (Subtarget->hasFp256()) {
12117     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12118     if (Res.getNode())
12119       return Res;
12120   }
12121
12122   return SDValue();
12123 }
12124
12125 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12126                                 SelectionDAG &DAG) {
12127   SDLoc DL(Op);
12128   MVT VT = Op.getSimpleValueType();
12129   SDValue In = Op.getOperand(0);
12130   MVT SVT = In.getSimpleValueType();
12131
12132   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12133     return LowerZERO_EXTEND_AVX512(Op, DAG);
12134
12135   if (Subtarget->hasFp256()) {
12136     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12137     if (Res.getNode())
12138       return Res;
12139   }
12140
12141   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12142          VT.getVectorNumElements() != SVT.getVectorNumElements());
12143   return SDValue();
12144 }
12145
12146 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12147   SDLoc DL(Op);
12148   MVT VT = Op.getSimpleValueType();
12149   SDValue In = Op.getOperand(0);
12150   MVT InVT = In.getSimpleValueType();
12151
12152   if (VT == MVT::i1) {
12153     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12154            "Invalid scalar TRUNCATE operation");
12155     if (InVT.getSizeInBits() >= 32)
12156       return SDValue();
12157     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12158     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12159   }
12160   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12161          "Invalid TRUNCATE operation");
12162
12163   // move vector to mask - truncate solution for SKX
12164   if (VT.getVectorElementType() == MVT::i1) {
12165     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12166         Subtarget->hasBWI())
12167       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12168     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12169         && InVT.getScalarSizeInBits() <= 16 &&
12170         Subtarget->hasBWI() && Subtarget->hasVLX())
12171       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12172     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12173         Subtarget->hasDQI())
12174       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12175     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12176         && InVT.getScalarSizeInBits() >= 32 &&
12177         Subtarget->hasDQI() && Subtarget->hasVLX())
12178       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12179   }
12180   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12181     if (VT.getVectorElementType().getSizeInBits() >=8)
12182       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12183
12184     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12185     unsigned NumElts = InVT.getVectorNumElements();
12186     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12187     if (InVT.getSizeInBits() < 512) {
12188       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12189       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12190       InVT = ExtVT;
12191     }
12192
12193     SDValue OneV =
12194      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12195     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12196     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12197   }
12198
12199   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12200     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12201     if (Subtarget->hasInt256()) {
12202       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12203       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12204       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12205                                 ShufMask);
12206       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12207                          DAG.getIntPtrConstant(0, DL));
12208     }
12209
12210     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12211                                DAG.getIntPtrConstant(0, DL));
12212     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12213                                DAG.getIntPtrConstant(2, DL));
12214     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12215     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12216     static const int ShufMask[] = {0, 2, 4, 6};
12217     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12218   }
12219
12220   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12221     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12222     if (Subtarget->hasInt256()) {
12223       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12224
12225       SmallVector<SDValue,32> pshufbMask;
12226       for (unsigned i = 0; i < 2; ++i) {
12227         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12228         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12229         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12230         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12231         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12232         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12233         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12234         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12235         for (unsigned j = 0; j < 8; ++j)
12236           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12237       }
12238       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12239       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12240       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12241
12242       static const int ShufMask[] = {0,  2,  -1,  -1};
12243       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12244                                 &ShufMask[0]);
12245       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12246                        DAG.getIntPtrConstant(0, DL));
12247       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12248     }
12249
12250     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12251                                DAG.getIntPtrConstant(0, DL));
12252
12253     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12254                                DAG.getIntPtrConstant(4, DL));
12255
12256     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12257     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12258
12259     // The PSHUFB mask:
12260     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12261                                    -1, -1, -1, -1, -1, -1, -1, -1};
12262
12263     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12264     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12265     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12266
12267     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12268     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12269
12270     // The MOVLHPS Mask:
12271     static const int ShufMask2[] = {0, 1, 4, 5};
12272     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12273     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12274   }
12275
12276   // Handle truncation of V256 to V128 using shuffles.
12277   if (!VT.is128BitVector() || !InVT.is256BitVector())
12278     return SDValue();
12279
12280   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12281
12282   unsigned NumElems = VT.getVectorNumElements();
12283   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12284
12285   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12286   // Prepare truncation shuffle mask
12287   for (unsigned i = 0; i != NumElems; ++i)
12288     MaskVec[i] = i * 2;
12289   SDValue V = DAG.getVectorShuffle(NVT, DL,
12290                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12291                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12292   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12293                      DAG.getIntPtrConstant(0, DL));
12294 }
12295
12296 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12297                                            SelectionDAG &DAG) const {
12298   assert(!Op.getSimpleValueType().isVector());
12299
12300   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12301     /*IsSigned=*/ true, /*IsReplace=*/ false);
12302   SDValue FIST = Vals.first, StackSlot = Vals.second;
12303   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12304   if (!FIST.getNode()) return Op;
12305
12306   if (StackSlot.getNode())
12307     // Load the result.
12308     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12309                        FIST, StackSlot, MachinePointerInfo(),
12310                        false, false, false, 0);
12311
12312   // The node is the result.
12313   return FIST;
12314 }
12315
12316 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12317                                            SelectionDAG &DAG) const {
12318   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12319     /*IsSigned=*/ false, /*IsReplace=*/ false);
12320   SDValue FIST = Vals.first, StackSlot = Vals.second;
12321   assert(FIST.getNode() && "Unexpected failure");
12322
12323   if (StackSlot.getNode())
12324     // Load the result.
12325     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12326                        FIST, StackSlot, MachinePointerInfo(),
12327                        false, false, false, 0);
12328
12329   // The node is the result.
12330   return FIST;
12331 }
12332
12333 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12334   SDLoc DL(Op);
12335   MVT VT = Op.getSimpleValueType();
12336   SDValue In = Op.getOperand(0);
12337   MVT SVT = In.getSimpleValueType();
12338
12339   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12340
12341   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12342                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12343                                  In, DAG.getUNDEF(SVT)));
12344 }
12345
12346 /// The only differences between FABS and FNEG are the mask and the logic op.
12347 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12348 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12349   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12350          "Wrong opcode for lowering FABS or FNEG.");
12351
12352   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12353
12354   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12355   // into an FNABS. We'll lower the FABS after that if it is still in use.
12356   if (IsFABS)
12357     for (SDNode *User : Op->uses())
12358       if (User->getOpcode() == ISD::FNEG)
12359         return Op;
12360
12361   SDValue Op0 = Op.getOperand(0);
12362   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12363
12364   SDLoc dl(Op);
12365   MVT VT = Op.getSimpleValueType();
12366   // Assume scalar op for initialization; update for vector if needed.
12367   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12368   // generate a 16-byte vector constant and logic op even for the scalar case.
12369   // Using a 16-byte mask allows folding the load of the mask with
12370   // the logic op, so it can save (~4 bytes) on code size.
12371   MVT EltVT = VT;
12372   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12373   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12374   // decide if we should generate a 16-byte constant mask when we only need 4 or
12375   // 8 bytes for the scalar case.
12376   if (VT.isVector()) {
12377     EltVT = VT.getVectorElementType();
12378     NumElts = VT.getVectorNumElements();
12379   }
12380
12381   unsigned EltBits = EltVT.getSizeInBits();
12382   LLVMContext *Context = DAG.getContext();
12383   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12384   APInt MaskElt =
12385     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12386   Constant *C = ConstantInt::get(*Context, MaskElt);
12387   C = ConstantVector::getSplat(NumElts, C);
12388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12389   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12390   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12391   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12392                              MachinePointerInfo::getConstantPool(),
12393                              false, false, false, Alignment);
12394
12395   if (VT.isVector()) {
12396     // For a vector, cast operands to a vector type, perform the logic op,
12397     // and cast the result back to the original value type.
12398     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12399     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12400     SDValue Operand = IsFNABS ?
12401       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12402       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12403     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12404     return DAG.getNode(ISD::BITCAST, dl, VT,
12405                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12406   }
12407
12408   // If not vector, then scalar.
12409   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12410   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12411   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12412 }
12413
12414 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12415   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12416   LLVMContext *Context = DAG.getContext();
12417   SDValue Op0 = Op.getOperand(0);
12418   SDValue Op1 = Op.getOperand(1);
12419   SDLoc dl(Op);
12420   MVT VT = Op.getSimpleValueType();
12421   MVT SrcVT = Op1.getSimpleValueType();
12422
12423   // If second operand is smaller, extend it first.
12424   if (SrcVT.bitsLT(VT)) {
12425     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12426     SrcVT = VT;
12427   }
12428   // And if it is bigger, shrink it first.
12429   if (SrcVT.bitsGT(VT)) {
12430     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12431     SrcVT = VT;
12432   }
12433
12434   // At this point the operands and the result should have the same
12435   // type, and that won't be f80 since that is not custom lowered.
12436
12437   const fltSemantics &Sem =
12438       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12439   const unsigned SizeInBits = VT.getSizeInBits();
12440
12441   SmallVector<Constant *, 4> CV(
12442       VT == MVT::f64 ? 2 : 4,
12443       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12444
12445   // First, clear all bits but the sign bit from the second operand (sign).
12446   CV[0] = ConstantFP::get(*Context,
12447                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12448   Constant *C = ConstantVector::get(CV);
12449   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12450   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12451                               MachinePointerInfo::getConstantPool(),
12452                               false, false, false, 16);
12453   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12454
12455   // Next, clear the sign bit from the first operand (magnitude).
12456   // If it's a constant, we can clear it here.
12457   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12458     APFloat APF = Op0CN->getValueAPF();
12459     // If the magnitude is a positive zero, the sign bit alone is enough.
12460     if (APF.isPosZero())
12461       return SignBit;
12462     APF.clearSign();
12463     CV[0] = ConstantFP::get(*Context, APF);
12464   } else {
12465     CV[0] = ConstantFP::get(
12466         *Context,
12467         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12468   }
12469   C = ConstantVector::get(CV);
12470   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12471   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12472                             MachinePointerInfo::getConstantPool(),
12473                             false, false, false, 16);
12474   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12475   if (!isa<ConstantFPSDNode>(Op0))
12476     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12477
12478   // OR the magnitude value with the sign bit.
12479   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12480 }
12481
12482 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12483   SDValue N0 = Op.getOperand(0);
12484   SDLoc dl(Op);
12485   MVT VT = Op.getSimpleValueType();
12486
12487   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12488   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12489                                   DAG.getConstant(1, dl, VT));
12490   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12491 }
12492
12493 // Check whether an OR'd tree is PTEST-able.
12494 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12495                                       SelectionDAG &DAG) {
12496   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12497
12498   if (!Subtarget->hasSSE41())
12499     return SDValue();
12500
12501   if (!Op->hasOneUse())
12502     return SDValue();
12503
12504   SDNode *N = Op.getNode();
12505   SDLoc DL(N);
12506
12507   SmallVector<SDValue, 8> Opnds;
12508   DenseMap<SDValue, unsigned> VecInMap;
12509   SmallVector<SDValue, 8> VecIns;
12510   EVT VT = MVT::Other;
12511
12512   // Recognize a special case where a vector is casted into wide integer to
12513   // test all 0s.
12514   Opnds.push_back(N->getOperand(0));
12515   Opnds.push_back(N->getOperand(1));
12516
12517   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12518     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12519     // BFS traverse all OR'd operands.
12520     if (I->getOpcode() == ISD::OR) {
12521       Opnds.push_back(I->getOperand(0));
12522       Opnds.push_back(I->getOperand(1));
12523       // Re-evaluate the number of nodes to be traversed.
12524       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12525       continue;
12526     }
12527
12528     // Quit if a non-EXTRACT_VECTOR_ELT
12529     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12530       return SDValue();
12531
12532     // Quit if without a constant index.
12533     SDValue Idx = I->getOperand(1);
12534     if (!isa<ConstantSDNode>(Idx))
12535       return SDValue();
12536
12537     SDValue ExtractedFromVec = I->getOperand(0);
12538     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12539     if (M == VecInMap.end()) {
12540       VT = ExtractedFromVec.getValueType();
12541       // Quit if not 128/256-bit vector.
12542       if (!VT.is128BitVector() && !VT.is256BitVector())
12543         return SDValue();
12544       // Quit if not the same type.
12545       if (VecInMap.begin() != VecInMap.end() &&
12546           VT != VecInMap.begin()->first.getValueType())
12547         return SDValue();
12548       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12549       VecIns.push_back(ExtractedFromVec);
12550     }
12551     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12552   }
12553
12554   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12555          "Not extracted from 128-/256-bit vector.");
12556
12557   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12558
12559   for (DenseMap<SDValue, unsigned>::const_iterator
12560         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12561     // Quit if not all elements are used.
12562     if (I->second != FullMask)
12563       return SDValue();
12564   }
12565
12566   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12567
12568   // Cast all vectors into TestVT for PTEST.
12569   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12570     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12571
12572   // If more than one full vectors are evaluated, OR them first before PTEST.
12573   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12574     // Each iteration will OR 2 nodes and append the result until there is only
12575     // 1 node left, i.e. the final OR'd value of all vectors.
12576     SDValue LHS = VecIns[Slot];
12577     SDValue RHS = VecIns[Slot + 1];
12578     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12579   }
12580
12581   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12582                      VecIns.back(), VecIns.back());
12583 }
12584
12585 /// \brief return true if \c Op has a use that doesn't just read flags.
12586 static bool hasNonFlagsUse(SDValue Op) {
12587   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12588        ++UI) {
12589     SDNode *User = *UI;
12590     unsigned UOpNo = UI.getOperandNo();
12591     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12592       // Look pass truncate.
12593       UOpNo = User->use_begin().getOperandNo();
12594       User = *User->use_begin();
12595     }
12596
12597     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12598         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12599       return true;
12600   }
12601   return false;
12602 }
12603
12604 /// Emit nodes that will be selected as "test Op0,Op0", or something
12605 /// equivalent.
12606 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12607                                     SelectionDAG &DAG) const {
12608   if (Op.getValueType() == MVT::i1) {
12609     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12610     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12611                        DAG.getConstant(0, dl, MVT::i8));
12612   }
12613   // CF and OF aren't always set the way we want. Determine which
12614   // of these we need.
12615   bool NeedCF = false;
12616   bool NeedOF = false;
12617   switch (X86CC) {
12618   default: break;
12619   case X86::COND_A: case X86::COND_AE:
12620   case X86::COND_B: case X86::COND_BE:
12621     NeedCF = true;
12622     break;
12623   case X86::COND_G: case X86::COND_GE:
12624   case X86::COND_L: case X86::COND_LE:
12625   case X86::COND_O: case X86::COND_NO: {
12626     // Check if we really need to set the
12627     // Overflow flag. If NoSignedWrap is present
12628     // that is not actually needed.
12629     switch (Op->getOpcode()) {
12630     case ISD::ADD:
12631     case ISD::SUB:
12632     case ISD::MUL:
12633     case ISD::SHL: {
12634       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12635       if (BinNode->Flags.hasNoSignedWrap())
12636         break;
12637     }
12638     default:
12639       NeedOF = true;
12640       break;
12641     }
12642     break;
12643   }
12644   }
12645   // See if we can use the EFLAGS value from the operand instead of
12646   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12647   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12648   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12649     // Emit a CMP with 0, which is the TEST pattern.
12650     //if (Op.getValueType() == MVT::i1)
12651     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12652     //                     DAG.getConstant(0, MVT::i1));
12653     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12654                        DAG.getConstant(0, dl, Op.getValueType()));
12655   }
12656   unsigned Opcode = 0;
12657   unsigned NumOperands = 0;
12658
12659   // Truncate operations may prevent the merge of the SETCC instruction
12660   // and the arithmetic instruction before it. Attempt to truncate the operands
12661   // of the arithmetic instruction and use a reduced bit-width instruction.
12662   bool NeedTruncation = false;
12663   SDValue ArithOp = Op;
12664   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12665     SDValue Arith = Op->getOperand(0);
12666     // Both the trunc and the arithmetic op need to have one user each.
12667     if (Arith->hasOneUse())
12668       switch (Arith.getOpcode()) {
12669         default: break;
12670         case ISD::ADD:
12671         case ISD::SUB:
12672         case ISD::AND:
12673         case ISD::OR:
12674         case ISD::XOR: {
12675           NeedTruncation = true;
12676           ArithOp = Arith;
12677         }
12678       }
12679   }
12680
12681   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12682   // which may be the result of a CAST.  We use the variable 'Op', which is the
12683   // non-casted variable when we check for possible users.
12684   switch (ArithOp.getOpcode()) {
12685   case ISD::ADD:
12686     // Due to an isel shortcoming, be conservative if this add is likely to be
12687     // selected as part of a load-modify-store instruction. When the root node
12688     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12689     // uses of other nodes in the match, such as the ADD in this case. This
12690     // leads to the ADD being left around and reselected, with the result being
12691     // two adds in the output.  Alas, even if none our users are stores, that
12692     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12693     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12694     // climbing the DAG back to the root, and it doesn't seem to be worth the
12695     // effort.
12696     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12697          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12698       if (UI->getOpcode() != ISD::CopyToReg &&
12699           UI->getOpcode() != ISD::SETCC &&
12700           UI->getOpcode() != ISD::STORE)
12701         goto default_case;
12702
12703     if (ConstantSDNode *C =
12704         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12705       // An add of one will be selected as an INC.
12706       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12707         Opcode = X86ISD::INC;
12708         NumOperands = 1;
12709         break;
12710       }
12711
12712       // An add of negative one (subtract of one) will be selected as a DEC.
12713       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12714         Opcode = X86ISD::DEC;
12715         NumOperands = 1;
12716         break;
12717       }
12718     }
12719
12720     // Otherwise use a regular EFLAGS-setting add.
12721     Opcode = X86ISD::ADD;
12722     NumOperands = 2;
12723     break;
12724   case ISD::SHL:
12725   case ISD::SRL:
12726     // If we have a constant logical shift that's only used in a comparison
12727     // against zero turn it into an equivalent AND. This allows turning it into
12728     // a TEST instruction later.
12729     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12730         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12731       EVT VT = Op.getValueType();
12732       unsigned BitWidth = VT.getSizeInBits();
12733       unsigned ShAmt = Op->getConstantOperandVal(1);
12734       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12735         break;
12736       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12737                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12738                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12739       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12740         break;
12741       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12742                                 DAG.getConstant(Mask, dl, VT));
12743       DAG.ReplaceAllUsesWith(Op, New);
12744       Op = New;
12745     }
12746     break;
12747
12748   case ISD::AND:
12749     // If the primary and result isn't used, don't bother using X86ISD::AND,
12750     // because a TEST instruction will be better.
12751     if (!hasNonFlagsUse(Op))
12752       break;
12753     // FALL THROUGH
12754   case ISD::SUB:
12755   case ISD::OR:
12756   case ISD::XOR:
12757     // Due to the ISEL shortcoming noted above, be conservative if this op is
12758     // likely to be selected as part of a load-modify-store instruction.
12759     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12760            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12761       if (UI->getOpcode() == ISD::STORE)
12762         goto default_case;
12763
12764     // Otherwise use a regular EFLAGS-setting instruction.
12765     switch (ArithOp.getOpcode()) {
12766     default: llvm_unreachable("unexpected operator!");
12767     case ISD::SUB: Opcode = X86ISD::SUB; break;
12768     case ISD::XOR: Opcode = X86ISD::XOR; break;
12769     case ISD::AND: Opcode = X86ISD::AND; break;
12770     case ISD::OR: {
12771       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12772         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12773         if (EFLAGS.getNode())
12774           return EFLAGS;
12775       }
12776       Opcode = X86ISD::OR;
12777       break;
12778     }
12779     }
12780
12781     NumOperands = 2;
12782     break;
12783   case X86ISD::ADD:
12784   case X86ISD::SUB:
12785   case X86ISD::INC:
12786   case X86ISD::DEC:
12787   case X86ISD::OR:
12788   case X86ISD::XOR:
12789   case X86ISD::AND:
12790     return SDValue(Op.getNode(), 1);
12791   default:
12792   default_case:
12793     break;
12794   }
12795
12796   // If we found that truncation is beneficial, perform the truncation and
12797   // update 'Op'.
12798   if (NeedTruncation) {
12799     EVT VT = Op.getValueType();
12800     SDValue WideVal = Op->getOperand(0);
12801     EVT WideVT = WideVal.getValueType();
12802     unsigned ConvertedOp = 0;
12803     // Use a target machine opcode to prevent further DAGCombine
12804     // optimizations that may separate the arithmetic operations
12805     // from the setcc node.
12806     switch (WideVal.getOpcode()) {
12807       default: break;
12808       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12809       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12810       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12811       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12812       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12813     }
12814
12815     if (ConvertedOp) {
12816       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12817       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12818         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12819         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12820         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12821       }
12822     }
12823   }
12824
12825   if (Opcode == 0)
12826     // Emit a CMP with 0, which is the TEST pattern.
12827     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12828                        DAG.getConstant(0, dl, Op.getValueType()));
12829
12830   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12831   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12832
12833   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12834   DAG.ReplaceAllUsesWith(Op, New);
12835   return SDValue(New.getNode(), 1);
12836 }
12837
12838 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12839 /// equivalent.
12840 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12841                                    SDLoc dl, SelectionDAG &DAG) const {
12842   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12843     if (C->getAPIntValue() == 0)
12844       return EmitTest(Op0, X86CC, dl, DAG);
12845
12846      if (Op0.getValueType() == MVT::i1)
12847        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12848   }
12849
12850   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12851        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12852     // Do the comparison at i32 if it's smaller, besides the Atom case.
12853     // This avoids subregister aliasing issues. Keep the smaller reference
12854     // if we're optimizing for size, however, as that'll allow better folding
12855     // of memory operations.
12856     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12857         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12858             Attribute::MinSize) &&
12859         !Subtarget->isAtom()) {
12860       unsigned ExtendOp =
12861           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12862       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12863       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12864     }
12865     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12866     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12867     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12868                               Op0, Op1);
12869     return SDValue(Sub.getNode(), 1);
12870   }
12871   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12872 }
12873
12874 /// Convert a comparison if required by the subtarget.
12875 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12876                                                  SelectionDAG &DAG) const {
12877   // If the subtarget does not support the FUCOMI instruction, floating-point
12878   // comparisons have to be converted.
12879   if (Subtarget->hasCMov() ||
12880       Cmp.getOpcode() != X86ISD::CMP ||
12881       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12882       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12883     return Cmp;
12884
12885   // The instruction selector will select an FUCOM instruction instead of
12886   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12887   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12888   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12889   SDLoc dl(Cmp);
12890   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12891   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12892   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12893                             DAG.getConstant(8, dl, MVT::i8));
12894   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12895   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12896 }
12897
12898 /// The minimum architected relative accuracy is 2^-12. We need one
12899 /// Newton-Raphson step to have a good float result (24 bits of precision).
12900 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12901                                             DAGCombinerInfo &DCI,
12902                                             unsigned &RefinementSteps,
12903                                             bool &UseOneConstNR) const {
12904   // FIXME: We should use instruction latency models to calculate the cost of
12905   // each potential sequence, but this is very hard to do reliably because
12906   // at least Intel's Core* chips have variable timing based on the number of
12907   // significant digits in the divisor and/or sqrt operand.
12908   if (!Subtarget->useSqrtEst())
12909     return SDValue();
12910
12911   EVT VT = Op.getValueType();
12912
12913   // SSE1 has rsqrtss and rsqrtps.
12914   // TODO: Add support for AVX512 (v16f32).
12915   // It is likely not profitable to do this for f64 because a double-precision
12916   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12917   // instructions: convert to single, rsqrtss, convert back to double, refine
12918   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12919   // along with FMA, this could be a throughput win.
12920   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12921       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12922     RefinementSteps = 1;
12923     UseOneConstNR = false;
12924     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12925   }
12926   return SDValue();
12927 }
12928
12929 /// The minimum architected relative accuracy is 2^-12. We need one
12930 /// Newton-Raphson step to have a good float result (24 bits of precision).
12931 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12932                                             DAGCombinerInfo &DCI,
12933                                             unsigned &RefinementSteps) const {
12934   // FIXME: We should use instruction latency models to calculate the cost of
12935   // each potential sequence, but this is very hard to do reliably because
12936   // at least Intel's Core* chips have variable timing based on the number of
12937   // significant digits in the divisor.
12938   if (!Subtarget->useReciprocalEst())
12939     return SDValue();
12940
12941   EVT VT = Op.getValueType();
12942
12943   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12944   // TODO: Add support for AVX512 (v16f32).
12945   // It is likely not profitable to do this for f64 because a double-precision
12946   // reciprocal estimate with refinement on x86 prior to FMA requires
12947   // 15 instructions: convert to single, rcpss, convert back to double, refine
12948   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12949   // along with FMA, this could be a throughput win.
12950   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12951       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12952     RefinementSteps = ReciprocalEstimateRefinementSteps;
12953     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12954   }
12955   return SDValue();
12956 }
12957
12958 /// If we have at least two divisions that use the same divisor, convert to
12959 /// multplication by a reciprocal. This may need to be adjusted for a given
12960 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12961 /// This is because we still need one division to calculate the reciprocal and
12962 /// then we need two multiplies by that reciprocal as replacements for the
12963 /// original divisions.
12964 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12965   return NumUsers > 1;
12966 }
12967
12968 static bool isAllOnes(SDValue V) {
12969   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12970   return C && C->isAllOnesValue();
12971 }
12972
12973 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12974 /// if it's possible.
12975 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12976                                      SDLoc dl, SelectionDAG &DAG) const {
12977   SDValue Op0 = And.getOperand(0);
12978   SDValue Op1 = And.getOperand(1);
12979   if (Op0.getOpcode() == ISD::TRUNCATE)
12980     Op0 = Op0.getOperand(0);
12981   if (Op1.getOpcode() == ISD::TRUNCATE)
12982     Op1 = Op1.getOperand(0);
12983
12984   SDValue LHS, RHS;
12985   if (Op1.getOpcode() == ISD::SHL)
12986     std::swap(Op0, Op1);
12987   if (Op0.getOpcode() == ISD::SHL) {
12988     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12989       if (And00C->getZExtValue() == 1) {
12990         // If we looked past a truncate, check that it's only truncating away
12991         // known zeros.
12992         unsigned BitWidth = Op0.getValueSizeInBits();
12993         unsigned AndBitWidth = And.getValueSizeInBits();
12994         if (BitWidth > AndBitWidth) {
12995           APInt Zeros, Ones;
12996           DAG.computeKnownBits(Op0, Zeros, Ones);
12997           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12998             return SDValue();
12999         }
13000         LHS = Op1;
13001         RHS = Op0.getOperand(1);
13002       }
13003   } else if (Op1.getOpcode() == ISD::Constant) {
13004     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13005     uint64_t AndRHSVal = AndRHS->getZExtValue();
13006     SDValue AndLHS = Op0;
13007
13008     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13009       LHS = AndLHS.getOperand(0);
13010       RHS = AndLHS.getOperand(1);
13011     }
13012
13013     // Use BT if the immediate can't be encoded in a TEST instruction.
13014     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13015       LHS = AndLHS;
13016       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13017     }
13018   }
13019
13020   if (LHS.getNode()) {
13021     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13022     // instruction.  Since the shift amount is in-range-or-undefined, we know
13023     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13024     // the encoding for the i16 version is larger than the i32 version.
13025     // Also promote i16 to i32 for performance / code size reason.
13026     if (LHS.getValueType() == MVT::i8 ||
13027         LHS.getValueType() == MVT::i16)
13028       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13029
13030     // If the operand types disagree, extend the shift amount to match.  Since
13031     // BT ignores high bits (like shifts) we can use anyextend.
13032     if (LHS.getValueType() != RHS.getValueType())
13033       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13034
13035     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13036     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13037     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13038                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13039   }
13040
13041   return SDValue();
13042 }
13043
13044 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13045 /// mask CMPs.
13046 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13047                               SDValue &Op1) {
13048   unsigned SSECC;
13049   bool Swap = false;
13050
13051   // SSE Condition code mapping:
13052   //  0 - EQ
13053   //  1 - LT
13054   //  2 - LE
13055   //  3 - UNORD
13056   //  4 - NEQ
13057   //  5 - NLT
13058   //  6 - NLE
13059   //  7 - ORD
13060   switch (SetCCOpcode) {
13061   default: llvm_unreachable("Unexpected SETCC condition");
13062   case ISD::SETOEQ:
13063   case ISD::SETEQ:  SSECC = 0; break;
13064   case ISD::SETOGT:
13065   case ISD::SETGT:  Swap = true; // Fallthrough
13066   case ISD::SETLT:
13067   case ISD::SETOLT: SSECC = 1; break;
13068   case ISD::SETOGE:
13069   case ISD::SETGE:  Swap = true; // Fallthrough
13070   case ISD::SETLE:
13071   case ISD::SETOLE: SSECC = 2; break;
13072   case ISD::SETUO:  SSECC = 3; break;
13073   case ISD::SETUNE:
13074   case ISD::SETNE:  SSECC = 4; break;
13075   case ISD::SETULE: Swap = true; // Fallthrough
13076   case ISD::SETUGE: SSECC = 5; break;
13077   case ISD::SETULT: Swap = true; // Fallthrough
13078   case ISD::SETUGT: SSECC = 6; break;
13079   case ISD::SETO:   SSECC = 7; break;
13080   case ISD::SETUEQ:
13081   case ISD::SETONE: SSECC = 8; break;
13082   }
13083   if (Swap)
13084     std::swap(Op0, Op1);
13085
13086   return SSECC;
13087 }
13088
13089 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13090 // ones, and then concatenate the result back.
13091 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13092   MVT VT = Op.getSimpleValueType();
13093
13094   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13095          "Unsupported value type for operation");
13096
13097   unsigned NumElems = VT.getVectorNumElements();
13098   SDLoc dl(Op);
13099   SDValue CC = Op.getOperand(2);
13100
13101   // Extract the LHS vectors
13102   SDValue LHS = Op.getOperand(0);
13103   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13104   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13105
13106   // Extract the RHS vectors
13107   SDValue RHS = Op.getOperand(1);
13108   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13109   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13110
13111   // Issue the operation on the smaller types and concatenate the result back
13112   MVT EltVT = VT.getVectorElementType();
13113   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13114   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13115                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13116                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13117 }
13118
13119 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13120   SDValue Op0 = Op.getOperand(0);
13121   SDValue Op1 = Op.getOperand(1);
13122   SDValue CC = Op.getOperand(2);
13123   MVT VT = Op.getSimpleValueType();
13124   SDLoc dl(Op);
13125
13126   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13127          "Unexpected type for boolean compare operation");
13128   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13129   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13130                                DAG.getConstant(-1, dl, VT));
13131   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13132                                DAG.getConstant(-1, dl, VT));
13133   switch (SetCCOpcode) {
13134   default: llvm_unreachable("Unexpected SETCC condition");
13135   case ISD::SETNE:
13136     // (x != y) -> ~(x ^ y)
13137     return DAG.getNode(ISD::XOR, dl, VT,
13138                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13139                        DAG.getConstant(-1, dl, VT));
13140   case ISD::SETEQ:
13141     // (x == y) -> (x ^ y)
13142     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13143   case ISD::SETUGT:
13144   case ISD::SETGT:
13145     // (x > y) -> (x & ~y)
13146     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13147   case ISD::SETULT:
13148   case ISD::SETLT:
13149     // (x < y) -> (~x & y)
13150     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13151   case ISD::SETULE:
13152   case ISD::SETLE:
13153     // (x <= y) -> (~x | y)
13154     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13155   case ISD::SETUGE:
13156   case ISD::SETGE:
13157     // (x >=y) -> (x | ~y)
13158     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13159   }
13160 }
13161
13162 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13163                                      const X86Subtarget *Subtarget) {
13164   SDValue Op0 = Op.getOperand(0);
13165   SDValue Op1 = Op.getOperand(1);
13166   SDValue CC = Op.getOperand(2);
13167   MVT VT = Op.getSimpleValueType();
13168   SDLoc dl(Op);
13169
13170   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13171          Op.getValueType().getScalarType() == MVT::i1 &&
13172          "Cannot set masked compare for this operation");
13173
13174   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13175   unsigned  Opc = 0;
13176   bool Unsigned = false;
13177   bool Swap = false;
13178   unsigned SSECC;
13179   switch (SetCCOpcode) {
13180   default: llvm_unreachable("Unexpected SETCC condition");
13181   case ISD::SETNE:  SSECC = 4; break;
13182   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13183   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13184   case ISD::SETLT:  Swap = true; //fall-through
13185   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13186   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13187   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13188   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13189   case ISD::SETULE: Unsigned = true; //fall-through
13190   case ISD::SETLE:  SSECC = 2; break;
13191   }
13192
13193   if (Swap)
13194     std::swap(Op0, Op1);
13195   if (Opc)
13196     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13197   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13198   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13199                      DAG.getConstant(SSECC, dl, MVT::i8));
13200 }
13201
13202 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13203 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13204 /// return an empty value.
13205 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13206 {
13207   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13208   if (!BV)
13209     return SDValue();
13210
13211   MVT VT = Op1.getSimpleValueType();
13212   MVT EVT = VT.getVectorElementType();
13213   unsigned n = VT.getVectorNumElements();
13214   SmallVector<SDValue, 8> ULTOp1;
13215
13216   for (unsigned i = 0; i < n; ++i) {
13217     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13218     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13219       return SDValue();
13220
13221     // Avoid underflow.
13222     APInt Val = Elt->getAPIntValue();
13223     if (Val == 0)
13224       return SDValue();
13225
13226     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13227   }
13228
13229   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13230 }
13231
13232 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13233                            SelectionDAG &DAG) {
13234   SDValue Op0 = Op.getOperand(0);
13235   SDValue Op1 = Op.getOperand(1);
13236   SDValue CC = Op.getOperand(2);
13237   MVT VT = Op.getSimpleValueType();
13238   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13239   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13240   SDLoc dl(Op);
13241
13242   if (isFP) {
13243 #ifndef NDEBUG
13244     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13245     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13246 #endif
13247
13248     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13249     unsigned Opc = X86ISD::CMPP;
13250     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13251       assert(VT.getVectorNumElements() <= 16);
13252       Opc = X86ISD::CMPM;
13253     }
13254     // In the two special cases we can't handle, emit two comparisons.
13255     if (SSECC == 8) {
13256       unsigned CC0, CC1;
13257       unsigned CombineOpc;
13258       if (SetCCOpcode == ISD::SETUEQ) {
13259         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13260       } else {
13261         assert(SetCCOpcode == ISD::SETONE);
13262         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13263       }
13264
13265       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13266                                  DAG.getConstant(CC0, dl, MVT::i8));
13267       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13268                                  DAG.getConstant(CC1, dl, MVT::i8));
13269       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13270     }
13271     // Handle all other FP comparisons here.
13272     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13273                        DAG.getConstant(SSECC, dl, MVT::i8));
13274   }
13275
13276   // Break 256-bit integer vector compare into smaller ones.
13277   if (VT.is256BitVector() && !Subtarget->hasInt256())
13278     return Lower256IntVSETCC(Op, DAG);
13279
13280   EVT OpVT = Op1.getValueType();
13281   if (OpVT.getVectorElementType() == MVT::i1)
13282     return LowerBoolVSETCC_AVX512(Op, DAG);
13283
13284   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13285   if (Subtarget->hasAVX512()) {
13286     if (Op1.getValueType().is512BitVector() ||
13287         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13288         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13289       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13290
13291     // In AVX-512 architecture setcc returns mask with i1 elements,
13292     // But there is no compare instruction for i8 and i16 elements in KNL.
13293     // We are not talking about 512-bit operands in this case, these
13294     // types are illegal.
13295     if (MaskResult &&
13296         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13297          OpVT.getVectorElementType().getSizeInBits() >= 8))
13298       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13299                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13300   }
13301
13302   // We are handling one of the integer comparisons here.  Since SSE only has
13303   // GT and EQ comparisons for integer, swapping operands and multiple
13304   // operations may be required for some comparisons.
13305   unsigned Opc;
13306   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13307   bool Subus = false;
13308
13309   switch (SetCCOpcode) {
13310   default: llvm_unreachable("Unexpected SETCC condition");
13311   case ISD::SETNE:  Invert = true;
13312   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13313   case ISD::SETLT:  Swap = true;
13314   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13315   case ISD::SETGE:  Swap = true;
13316   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13317                     Invert = true; break;
13318   case ISD::SETULT: Swap = true;
13319   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13320                     FlipSigns = true; break;
13321   case ISD::SETUGE: Swap = true;
13322   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13323                     FlipSigns = true; Invert = true; break;
13324   }
13325
13326   // Special case: Use min/max operations for SETULE/SETUGE
13327   MVT VET = VT.getVectorElementType();
13328   bool hasMinMax =
13329        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13330     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13331
13332   if (hasMinMax) {
13333     switch (SetCCOpcode) {
13334     default: break;
13335     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13336     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13337     }
13338
13339     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13340   }
13341
13342   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13343   if (!MinMax && hasSubus) {
13344     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13345     // Op0 u<= Op1:
13346     //   t = psubus Op0, Op1
13347     //   pcmpeq t, <0..0>
13348     switch (SetCCOpcode) {
13349     default: break;
13350     case ISD::SETULT: {
13351       // If the comparison is against a constant we can turn this into a
13352       // setule.  With psubus, setule does not require a swap.  This is
13353       // beneficial because the constant in the register is no longer
13354       // destructed as the destination so it can be hoisted out of a loop.
13355       // Only do this pre-AVX since vpcmp* is no longer destructive.
13356       if (Subtarget->hasAVX())
13357         break;
13358       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13359       if (ULEOp1.getNode()) {
13360         Op1 = ULEOp1;
13361         Subus = true; Invert = false; Swap = false;
13362       }
13363       break;
13364     }
13365     // Psubus is better than flip-sign because it requires no inversion.
13366     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13367     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13368     }
13369
13370     if (Subus) {
13371       Opc = X86ISD::SUBUS;
13372       FlipSigns = false;
13373     }
13374   }
13375
13376   if (Swap)
13377     std::swap(Op0, Op1);
13378
13379   // Check that the operation in question is available (most are plain SSE2,
13380   // but PCMPGTQ and PCMPEQQ have different requirements).
13381   if (VT == MVT::v2i64) {
13382     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13383       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13384
13385       // First cast everything to the right type.
13386       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13387       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13388
13389       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13390       // bits of the inputs before performing those operations. The lower
13391       // compare is always unsigned.
13392       SDValue SB;
13393       if (FlipSigns) {
13394         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13395       } else {
13396         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13397         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13398         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13399                          Sign, Zero, Sign, Zero);
13400       }
13401       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13402       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13403
13404       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13405       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13406       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13407
13408       // Create masks for only the low parts/high parts of the 64 bit integers.
13409       static const int MaskHi[] = { 1, 1, 3, 3 };
13410       static const int MaskLo[] = { 0, 0, 2, 2 };
13411       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13412       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13413       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13414
13415       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13416       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13417
13418       if (Invert)
13419         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13420
13421       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13422     }
13423
13424     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13425       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13426       // pcmpeqd + pshufd + pand.
13427       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13428
13429       // First cast everything to the right type.
13430       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13431       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13432
13433       // Do the compare.
13434       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13435
13436       // Make sure the lower and upper halves are both all-ones.
13437       static const int Mask[] = { 1, 0, 3, 2 };
13438       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13439       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13440
13441       if (Invert)
13442         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13443
13444       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13445     }
13446   }
13447
13448   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13449   // bits of the inputs before performing those operations.
13450   if (FlipSigns) {
13451     EVT EltVT = VT.getVectorElementType();
13452     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13453                                  VT);
13454     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13455     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13456   }
13457
13458   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13459
13460   // If the logical-not of the result is required, perform that now.
13461   if (Invert)
13462     Result = DAG.getNOT(dl, Result, VT);
13463
13464   if (MinMax)
13465     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13466
13467   if (Subus)
13468     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13469                          getZeroVector(VT, Subtarget, DAG, dl));
13470
13471   return Result;
13472 }
13473
13474 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13475
13476   MVT VT = Op.getSimpleValueType();
13477
13478   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13479
13480   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13481          && "SetCC type must be 8-bit or 1-bit integer");
13482   SDValue Op0 = Op.getOperand(0);
13483   SDValue Op1 = Op.getOperand(1);
13484   SDLoc dl(Op);
13485   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13486
13487   // Optimize to BT if possible.
13488   // Lower (X & (1 << N)) == 0 to BT(X, N).
13489   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13490   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13491   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13492       Op1.getOpcode() == ISD::Constant &&
13493       cast<ConstantSDNode>(Op1)->isNullValue() &&
13494       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13495     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13496     if (NewSetCC.getNode()) {
13497       if (VT == MVT::i1)
13498         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13499       return NewSetCC;
13500     }
13501   }
13502
13503   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13504   // these.
13505   if (Op1.getOpcode() == ISD::Constant &&
13506       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13507        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13508       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13509
13510     // If the input is a setcc, then reuse the input setcc or use a new one with
13511     // the inverted condition.
13512     if (Op0.getOpcode() == X86ISD::SETCC) {
13513       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13514       bool Invert = (CC == ISD::SETNE) ^
13515         cast<ConstantSDNode>(Op1)->isNullValue();
13516       if (!Invert)
13517         return Op0;
13518
13519       CCode = X86::GetOppositeBranchCondition(CCode);
13520       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13521                                   DAG.getConstant(CCode, dl, MVT::i8),
13522                                   Op0.getOperand(1));
13523       if (VT == MVT::i1)
13524         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13525       return SetCC;
13526     }
13527   }
13528   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13529       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13530       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13531
13532     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13533     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13534   }
13535
13536   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13537   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13538   if (X86CC == X86::COND_INVALID)
13539     return SDValue();
13540
13541   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13542   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13543   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13544                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13545   if (VT == MVT::i1)
13546     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13547   return SetCC;
13548 }
13549
13550 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13551 static bool isX86LogicalCmp(SDValue Op) {
13552   unsigned Opc = Op.getNode()->getOpcode();
13553   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13554       Opc == X86ISD::SAHF)
13555     return true;
13556   if (Op.getResNo() == 1 &&
13557       (Opc == X86ISD::ADD ||
13558        Opc == X86ISD::SUB ||
13559        Opc == X86ISD::ADC ||
13560        Opc == X86ISD::SBB ||
13561        Opc == X86ISD::SMUL ||
13562        Opc == X86ISD::UMUL ||
13563        Opc == X86ISD::INC ||
13564        Opc == X86ISD::DEC ||
13565        Opc == X86ISD::OR ||
13566        Opc == X86ISD::XOR ||
13567        Opc == X86ISD::AND))
13568     return true;
13569
13570   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13571     return true;
13572
13573   return false;
13574 }
13575
13576 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13577   if (V.getOpcode() != ISD::TRUNCATE)
13578     return false;
13579
13580   SDValue VOp0 = V.getOperand(0);
13581   unsigned InBits = VOp0.getValueSizeInBits();
13582   unsigned Bits = V.getValueSizeInBits();
13583   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13584 }
13585
13586 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13587   bool addTest = true;
13588   SDValue Cond  = Op.getOperand(0);
13589   SDValue Op1 = Op.getOperand(1);
13590   SDValue Op2 = Op.getOperand(2);
13591   SDLoc DL(Op);
13592   EVT VT = Op1.getValueType();
13593   SDValue CC;
13594
13595   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13596   // are available or VBLENDV if AVX is available.
13597   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13598   if (Cond.getOpcode() == ISD::SETCC &&
13599       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13600        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13601       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13602     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13603     int SSECC = translateX86FSETCC(
13604         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13605
13606     if (SSECC != 8) {
13607       if (Subtarget->hasAVX512()) {
13608         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13609                                   DAG.getConstant(SSECC, DL, MVT::i8));
13610         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13611       }
13612
13613       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13614                                 DAG.getConstant(SSECC, DL, MVT::i8));
13615
13616       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13617       // of 3 logic instructions for size savings and potentially speed.
13618       // Unfortunately, there is no scalar form of VBLENDV.
13619
13620       // If either operand is a constant, don't try this. We can expect to
13621       // optimize away at least one of the logic instructions later in that
13622       // case, so that sequence would be faster than a variable blend.
13623
13624       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13625       // uses XMM0 as the selection register. That may need just as many
13626       // instructions as the AND/ANDN/OR sequence due to register moves, so
13627       // don't bother.
13628
13629       if (Subtarget->hasAVX() &&
13630           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13631
13632         // Convert to vectors, do a VSELECT, and convert back to scalar.
13633         // All of the conversions should be optimized away.
13634
13635         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13636         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13637         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13638         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13639
13640         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13641         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13642
13643         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13644
13645         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13646                            VSel, DAG.getIntPtrConstant(0, DL));
13647       }
13648       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13649       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13650       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13651     }
13652   }
13653
13654     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13655       SDValue Op1Scalar;
13656       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13657         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13658       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13659         Op1Scalar = Op1.getOperand(0);
13660       SDValue Op2Scalar;
13661       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13662         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13663       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13664         Op2Scalar = Op2.getOperand(0);
13665       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13666         SDValue newSelect = DAG.getNode(ISD::SELECT, DL, 
13667                                         Op1Scalar.getValueType(),
13668                                         Cond, Op1Scalar, Op2Scalar);
13669         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13670           return DAG.getNode(ISD::BITCAST, DL, VT, newSelect);
13671         SDValue ExtVec = DAG.getNode(ISD::BITCAST, DL, MVT::v8i1, newSelect);
13672         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13673                            DAG.getIntPtrConstant(0, DL));
13674     }
13675   }
13676
13677   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13678     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13679     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13680                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13681     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13682                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13683     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13684                                     Cond, Op1, Op2);
13685     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13686   }
13687
13688   if (Cond.getOpcode() == ISD::SETCC) {
13689     SDValue NewCond = LowerSETCC(Cond, DAG);
13690     if (NewCond.getNode())
13691       Cond = NewCond;
13692   }
13693
13694   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13695   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13696   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13697   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13698   if (Cond.getOpcode() == X86ISD::SETCC &&
13699       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13700       isZero(Cond.getOperand(1).getOperand(1))) {
13701     SDValue Cmp = Cond.getOperand(1);
13702
13703     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13704
13705     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13706         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13707       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13708
13709       SDValue CmpOp0 = Cmp.getOperand(0);
13710       // Apply further optimizations for special cases
13711       // (select (x != 0), -1, 0) -> neg & sbb
13712       // (select (x == 0), 0, -1) -> neg & sbb
13713       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13714         if (YC->isNullValue() &&
13715             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13716           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13717           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13718                                     DAG.getConstant(0, DL,
13719                                                     CmpOp0.getValueType()),
13720                                     CmpOp0);
13721           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13722                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13723                                     SDValue(Neg.getNode(), 1));
13724           return Res;
13725         }
13726
13727       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13728                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13729       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13730
13731       SDValue Res =   // Res = 0 or -1.
13732         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13733                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13734
13735       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13736         Res = DAG.getNOT(DL, Res, Res.getValueType());
13737
13738       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13739       if (!N2C || !N2C->isNullValue())
13740         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13741       return Res;
13742     }
13743   }
13744
13745   // Look past (and (setcc_carry (cmp ...)), 1).
13746   if (Cond.getOpcode() == ISD::AND &&
13747       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13748     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13749     if (C && C->getAPIntValue() == 1)
13750       Cond = Cond.getOperand(0);
13751   }
13752
13753   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13754   // setting operand in place of the X86ISD::SETCC.
13755   unsigned CondOpcode = Cond.getOpcode();
13756   if (CondOpcode == X86ISD::SETCC ||
13757       CondOpcode == X86ISD::SETCC_CARRY) {
13758     CC = Cond.getOperand(0);
13759
13760     SDValue Cmp = Cond.getOperand(1);
13761     unsigned Opc = Cmp.getOpcode();
13762     MVT VT = Op.getSimpleValueType();
13763
13764     bool IllegalFPCMov = false;
13765     if (VT.isFloatingPoint() && !VT.isVector() &&
13766         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13767       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13768
13769     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13770         Opc == X86ISD::BT) { // FIXME
13771       Cond = Cmp;
13772       addTest = false;
13773     }
13774   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13775              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13776              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13777               Cond.getOperand(0).getValueType() != MVT::i8)) {
13778     SDValue LHS = Cond.getOperand(0);
13779     SDValue RHS = Cond.getOperand(1);
13780     unsigned X86Opcode;
13781     unsigned X86Cond;
13782     SDVTList VTs;
13783     switch (CondOpcode) {
13784     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13785     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13786     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13787     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13788     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13789     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13790     default: llvm_unreachable("unexpected overflowing operator");
13791     }
13792     if (CondOpcode == ISD::UMULO)
13793       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13794                           MVT::i32);
13795     else
13796       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13797
13798     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13799
13800     if (CondOpcode == ISD::UMULO)
13801       Cond = X86Op.getValue(2);
13802     else
13803       Cond = X86Op.getValue(1);
13804
13805     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13806     addTest = false;
13807   }
13808
13809   if (addTest) {
13810     // Look pass the truncate if the high bits are known zero.
13811     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13812         Cond = Cond.getOperand(0);
13813
13814     // We know the result of AND is compared against zero. Try to match
13815     // it to BT.
13816     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13817       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13818       if (NewSetCC.getNode()) {
13819         CC = NewSetCC.getOperand(0);
13820         Cond = NewSetCC.getOperand(1);
13821         addTest = false;
13822       }
13823     }
13824   }
13825
13826   if (addTest) {
13827     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13828     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13829   }
13830
13831   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13832   // a <  b ?  0 : -1 -> RES = setcc_carry
13833   // a >= b ? -1 :  0 -> RES = setcc_carry
13834   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13835   if (Cond.getOpcode() == X86ISD::SUB) {
13836     Cond = ConvertCmpIfNecessary(Cond, DAG);
13837     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13838
13839     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13840         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13841       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13842                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13843                                 Cond);
13844       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13845         return DAG.getNOT(DL, Res, Res.getValueType());
13846       return Res;
13847     }
13848   }
13849
13850   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13851   // widen the cmov and push the truncate through. This avoids introducing a new
13852   // branch during isel and doesn't add any extensions.
13853   if (Op.getValueType() == MVT::i8 &&
13854       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13855     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13856     if (T1.getValueType() == T2.getValueType() &&
13857         // Blacklist CopyFromReg to avoid partial register stalls.
13858         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13859       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13860       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13861       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13862     }
13863   }
13864
13865   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13866   // condition is true.
13867   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13868   SDValue Ops[] = { Op2, Op1, CC, Cond };
13869   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13870 }
13871
13872 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13873                                        SelectionDAG &DAG) {
13874   MVT VT = Op->getSimpleValueType(0);
13875   SDValue In = Op->getOperand(0);
13876   MVT InVT = In.getSimpleValueType();
13877   MVT VTElt = VT.getVectorElementType();
13878   MVT InVTElt = InVT.getVectorElementType();
13879   SDLoc dl(Op);
13880
13881   // SKX processor
13882   if ((InVTElt == MVT::i1) &&
13883       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13884         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13885
13886        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13887         VTElt.getSizeInBits() <= 16)) ||
13888
13889        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13890         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13891
13892        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13893         VTElt.getSizeInBits() >= 32))))
13894     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13895
13896   unsigned int NumElts = VT.getVectorNumElements();
13897
13898   if (NumElts != 8 && NumElts != 16)
13899     return SDValue();
13900
13901   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13902     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13903       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13904     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13905   }
13906
13907   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13908   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13909   SDValue NegOne =
13910    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13911                    ExtVT);
13912   SDValue Zero =
13913    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13914
13915   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13916   if (VT.is512BitVector())
13917     return V;
13918   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13919 }
13920
13921 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
13922                                              const X86Subtarget *Subtarget,
13923                                              SelectionDAG &DAG) {
13924   SDValue In = Op->getOperand(0);
13925   MVT VT = Op->getSimpleValueType(0);
13926   MVT InVT = In.getSimpleValueType();
13927   assert(VT.getSizeInBits() == InVT.getSizeInBits());
13928
13929   MVT InSVT = InVT.getScalarType();
13930   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
13931
13932   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13933     return SDValue();
13934   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
13935     return SDValue();
13936
13937   SDLoc dl(Op);
13938
13939   // SSE41 targets can use the pmovsx* instructions directly.
13940   if (Subtarget->hasSSE41())
13941     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13942
13943   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
13944   SDValue Curr = In;
13945   MVT CurrVT = InVT;
13946
13947   // As SRAI is only available on i16/i32 types, we expand only up to i32
13948   // and handle i64 separately.
13949   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
13950     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
13951     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
13952     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
13953     Curr = DAG.getNode(ISD::BITCAST, dl, CurrVT, Curr);
13954   }
13955
13956   SDValue SignExt = Curr;
13957   if (CurrVT != InVT) {
13958     unsigned SignExtShift =
13959         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
13960     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13961                           DAG.getConstant(SignExtShift, dl, MVT::i8));
13962   }
13963
13964   if (CurrVT == VT)
13965     return SignExt;
13966
13967   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
13968     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13969                                DAG.getConstant(31, dl, MVT::i8));
13970     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
13971     return DAG.getNode(ISD::BITCAST, dl, VT, Ext);
13972   }
13973
13974   return SDValue();
13975 }
13976
13977 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13978                                 SelectionDAG &DAG) {
13979   MVT VT = Op->getSimpleValueType(0);
13980   SDValue In = Op->getOperand(0);
13981   MVT InVT = In.getSimpleValueType();
13982   SDLoc dl(Op);
13983
13984   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13985     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13986
13987   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13988       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13989       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13990     return SDValue();
13991
13992   if (Subtarget->hasInt256())
13993     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13994
13995   // Optimize vectors in AVX mode
13996   // Sign extend  v8i16 to v8i32 and
13997   //              v4i32 to v4i64
13998   //
13999   // Divide input vector into two parts
14000   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14001   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14002   // concat the vectors to original VT
14003
14004   unsigned NumElems = InVT.getVectorNumElements();
14005   SDValue Undef = DAG.getUNDEF(InVT);
14006
14007   SmallVector<int,8> ShufMask1(NumElems, -1);
14008   for (unsigned i = 0; i != NumElems/2; ++i)
14009     ShufMask1[i] = i;
14010
14011   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14012
14013   SmallVector<int,8> ShufMask2(NumElems, -1);
14014   for (unsigned i = 0; i != NumElems/2; ++i)
14015     ShufMask2[i] = i + NumElems/2;
14016
14017   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14018
14019   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14020                                 VT.getVectorNumElements()/2);
14021
14022   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14023   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14024
14025   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14026 }
14027
14028 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14029 // may emit an illegal shuffle but the expansion is still better than scalar
14030 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14031 // we'll emit a shuffle and a arithmetic shift.
14032 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14033 // TODO: It is possible to support ZExt by zeroing the undef values during
14034 // the shuffle phase or after the shuffle.
14035 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14036                                  SelectionDAG &DAG) {
14037   MVT RegVT = Op.getSimpleValueType();
14038   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14039   assert(RegVT.isInteger() &&
14040          "We only custom lower integer vector sext loads.");
14041
14042   // Nothing useful we can do without SSE2 shuffles.
14043   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14044
14045   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14046   SDLoc dl(Ld);
14047   EVT MemVT = Ld->getMemoryVT();
14048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14049   unsigned RegSz = RegVT.getSizeInBits();
14050
14051   ISD::LoadExtType Ext = Ld->getExtensionType();
14052
14053   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14054          && "Only anyext and sext are currently implemented.");
14055   assert(MemVT != RegVT && "Cannot extend to the same type");
14056   assert(MemVT.isVector() && "Must load a vector from memory");
14057
14058   unsigned NumElems = RegVT.getVectorNumElements();
14059   unsigned MemSz = MemVT.getSizeInBits();
14060   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14061
14062   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14063     // The only way in which we have a legal 256-bit vector result but not the
14064     // integer 256-bit operations needed to directly lower a sextload is if we
14065     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14066     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14067     // correctly legalized. We do this late to allow the canonical form of
14068     // sextload to persist throughout the rest of the DAG combiner -- it wants
14069     // to fold together any extensions it can, and so will fuse a sign_extend
14070     // of an sextload into a sextload targeting a wider value.
14071     SDValue Load;
14072     if (MemSz == 128) {
14073       // Just switch this to a normal load.
14074       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14075                                        "it must be a legal 128-bit vector "
14076                                        "type!");
14077       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14078                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14079                   Ld->isInvariant(), Ld->getAlignment());
14080     } else {
14081       assert(MemSz < 128 &&
14082              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14083       // Do an sext load to a 128-bit vector type. We want to use the same
14084       // number of elements, but elements half as wide. This will end up being
14085       // recursively lowered by this routine, but will succeed as we definitely
14086       // have all the necessary features if we're using AVX1.
14087       EVT HalfEltVT =
14088           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14089       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14090       Load =
14091           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14092                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14093                          Ld->isNonTemporal(), Ld->isInvariant(),
14094                          Ld->getAlignment());
14095     }
14096
14097     // Replace chain users with the new chain.
14098     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14099     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14100
14101     // Finally, do a normal sign-extend to the desired register.
14102     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14103   }
14104
14105   // All sizes must be a power of two.
14106   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14107          "Non-power-of-two elements are not custom lowered!");
14108
14109   // Attempt to load the original value using scalar loads.
14110   // Find the largest scalar type that divides the total loaded size.
14111   MVT SclrLoadTy = MVT::i8;
14112   for (MVT Tp : MVT::integer_valuetypes()) {
14113     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14114       SclrLoadTy = Tp;
14115     }
14116   }
14117
14118   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14119   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14120       (64 <= MemSz))
14121     SclrLoadTy = MVT::f64;
14122
14123   // Calculate the number of scalar loads that we need to perform
14124   // in order to load our vector from memory.
14125   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14126
14127   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14128          "Can only lower sext loads with a single scalar load!");
14129
14130   unsigned loadRegZize = RegSz;
14131   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14132     loadRegZize = 128;
14133
14134   // Represent our vector as a sequence of elements which are the
14135   // largest scalar that we can load.
14136   EVT LoadUnitVecVT = EVT::getVectorVT(
14137       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14138
14139   // Represent the data using the same element type that is stored in
14140   // memory. In practice, we ''widen'' MemVT.
14141   EVT WideVecVT =
14142       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14143                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14144
14145   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14146          "Invalid vector type");
14147
14148   // We can't shuffle using an illegal type.
14149   assert(TLI.isTypeLegal(WideVecVT) &&
14150          "We only lower types that form legal widened vector types");
14151
14152   SmallVector<SDValue, 8> Chains;
14153   SDValue Ptr = Ld->getBasePtr();
14154   SDValue Increment =
14155       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14156   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14157
14158   for (unsigned i = 0; i < NumLoads; ++i) {
14159     // Perform a single load.
14160     SDValue ScalarLoad =
14161         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14162                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14163                     Ld->getAlignment());
14164     Chains.push_back(ScalarLoad.getValue(1));
14165     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14166     // another round of DAGCombining.
14167     if (i == 0)
14168       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14169     else
14170       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14171                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14172
14173     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14174   }
14175
14176   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14177
14178   // Bitcast the loaded value to a vector of the original element type, in
14179   // the size of the target vector type.
14180   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14181   unsigned SizeRatio = RegSz / MemSz;
14182
14183   if (Ext == ISD::SEXTLOAD) {
14184     // If we have SSE4.1, we can directly emit a VSEXT node.
14185     if (Subtarget->hasSSE41()) {
14186       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14187       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14188       return Sext;
14189     }
14190
14191     // Otherwise we'll shuffle the small elements in the high bits of the
14192     // larger type and perform an arithmetic shift. If the shift is not legal
14193     // it's better to scalarize.
14194     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14195            "We can't implement a sext load without an arithmetic right shift!");
14196
14197     // Redistribute the loaded elements into the different locations.
14198     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14199     for (unsigned i = 0; i != NumElems; ++i)
14200       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14201
14202     SDValue Shuff = DAG.getVectorShuffle(
14203         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14204
14205     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14206
14207     // Build the arithmetic shift.
14208     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14209                    MemVT.getVectorElementType().getSizeInBits();
14210     Shuff =
14211         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14212                     DAG.getConstant(Amt, dl, RegVT));
14213
14214     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14215     return Shuff;
14216   }
14217
14218   // Redistribute the loaded elements into the different locations.
14219   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14220   for (unsigned i = 0; i != NumElems; ++i)
14221     ShuffleVec[i * SizeRatio] = i;
14222
14223   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14224                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14225
14226   // Bitcast to the requested type.
14227   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14228   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14229   return Shuff;
14230 }
14231
14232 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14233 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14234 // from the AND / OR.
14235 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14236   Opc = Op.getOpcode();
14237   if (Opc != ISD::OR && Opc != ISD::AND)
14238     return false;
14239   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14240           Op.getOperand(0).hasOneUse() &&
14241           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14242           Op.getOperand(1).hasOneUse());
14243 }
14244
14245 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14246 // 1 and that the SETCC node has a single use.
14247 static bool isXor1OfSetCC(SDValue Op) {
14248   if (Op.getOpcode() != ISD::XOR)
14249     return false;
14250   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14251   if (N1C && N1C->getAPIntValue() == 1) {
14252     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14253       Op.getOperand(0).hasOneUse();
14254   }
14255   return false;
14256 }
14257
14258 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14259   bool addTest = true;
14260   SDValue Chain = Op.getOperand(0);
14261   SDValue Cond  = Op.getOperand(1);
14262   SDValue Dest  = Op.getOperand(2);
14263   SDLoc dl(Op);
14264   SDValue CC;
14265   bool Inverted = false;
14266
14267   if (Cond.getOpcode() == ISD::SETCC) {
14268     // Check for setcc([su]{add,sub,mul}o == 0).
14269     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14270         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14271         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14272         Cond.getOperand(0).getResNo() == 1 &&
14273         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14274          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14275          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14276          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14277          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14278          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14279       Inverted = true;
14280       Cond = Cond.getOperand(0);
14281     } else {
14282       SDValue NewCond = LowerSETCC(Cond, DAG);
14283       if (NewCond.getNode())
14284         Cond = NewCond;
14285     }
14286   }
14287 #if 0
14288   // FIXME: LowerXALUO doesn't handle these!!
14289   else if (Cond.getOpcode() == X86ISD::ADD  ||
14290            Cond.getOpcode() == X86ISD::SUB  ||
14291            Cond.getOpcode() == X86ISD::SMUL ||
14292            Cond.getOpcode() == X86ISD::UMUL)
14293     Cond = LowerXALUO(Cond, DAG);
14294 #endif
14295
14296   // Look pass (and (setcc_carry (cmp ...)), 1).
14297   if (Cond.getOpcode() == ISD::AND &&
14298       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14299     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14300     if (C && C->getAPIntValue() == 1)
14301       Cond = Cond.getOperand(0);
14302   }
14303
14304   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14305   // setting operand in place of the X86ISD::SETCC.
14306   unsigned CondOpcode = Cond.getOpcode();
14307   if (CondOpcode == X86ISD::SETCC ||
14308       CondOpcode == X86ISD::SETCC_CARRY) {
14309     CC = Cond.getOperand(0);
14310
14311     SDValue Cmp = Cond.getOperand(1);
14312     unsigned Opc = Cmp.getOpcode();
14313     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14314     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14315       Cond = Cmp;
14316       addTest = false;
14317     } else {
14318       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14319       default: break;
14320       case X86::COND_O:
14321       case X86::COND_B:
14322         // These can only come from an arithmetic instruction with overflow,
14323         // e.g. SADDO, UADDO.
14324         Cond = Cond.getNode()->getOperand(1);
14325         addTest = false;
14326         break;
14327       }
14328     }
14329   }
14330   CondOpcode = Cond.getOpcode();
14331   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14332       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14333       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14334        Cond.getOperand(0).getValueType() != MVT::i8)) {
14335     SDValue LHS = Cond.getOperand(0);
14336     SDValue RHS = Cond.getOperand(1);
14337     unsigned X86Opcode;
14338     unsigned X86Cond;
14339     SDVTList VTs;
14340     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14341     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14342     // X86ISD::INC).
14343     switch (CondOpcode) {
14344     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14345     case ISD::SADDO:
14346       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14347         if (C->isOne()) {
14348           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14349           break;
14350         }
14351       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14352     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14353     case ISD::SSUBO:
14354       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14355         if (C->isOne()) {
14356           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14357           break;
14358         }
14359       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14360     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14361     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14362     default: llvm_unreachable("unexpected overflowing operator");
14363     }
14364     if (Inverted)
14365       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14366     if (CondOpcode == ISD::UMULO)
14367       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14368                           MVT::i32);
14369     else
14370       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14371
14372     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14373
14374     if (CondOpcode == ISD::UMULO)
14375       Cond = X86Op.getValue(2);
14376     else
14377       Cond = X86Op.getValue(1);
14378
14379     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14380     addTest = false;
14381   } else {
14382     unsigned CondOpc;
14383     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14384       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14385       if (CondOpc == ISD::OR) {
14386         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14387         // two branches instead of an explicit OR instruction with a
14388         // separate test.
14389         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14390             isX86LogicalCmp(Cmp)) {
14391           CC = Cond.getOperand(0).getOperand(0);
14392           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14393                               Chain, Dest, CC, Cmp);
14394           CC = Cond.getOperand(1).getOperand(0);
14395           Cond = Cmp;
14396           addTest = false;
14397         }
14398       } else { // ISD::AND
14399         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14400         // two branches instead of an explicit AND instruction with a
14401         // separate test. However, we only do this if this block doesn't
14402         // have a fall-through edge, because this requires an explicit
14403         // jmp when the condition is false.
14404         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14405             isX86LogicalCmp(Cmp) &&
14406             Op.getNode()->hasOneUse()) {
14407           X86::CondCode CCode =
14408             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14409           CCode = X86::GetOppositeBranchCondition(CCode);
14410           CC = DAG.getConstant(CCode, dl, MVT::i8);
14411           SDNode *User = *Op.getNode()->use_begin();
14412           // Look for an unconditional branch following this conditional branch.
14413           // We need this because we need to reverse the successors in order
14414           // to implement FCMP_OEQ.
14415           if (User->getOpcode() == ISD::BR) {
14416             SDValue FalseBB = User->getOperand(1);
14417             SDNode *NewBR =
14418               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14419             assert(NewBR == User);
14420             (void)NewBR;
14421             Dest = FalseBB;
14422
14423             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14424                                 Chain, Dest, CC, Cmp);
14425             X86::CondCode CCode =
14426               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14427             CCode = X86::GetOppositeBranchCondition(CCode);
14428             CC = DAG.getConstant(CCode, dl, MVT::i8);
14429             Cond = Cmp;
14430             addTest = false;
14431           }
14432         }
14433       }
14434     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14435       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14436       // It should be transformed during dag combiner except when the condition
14437       // is set by a arithmetics with overflow node.
14438       X86::CondCode CCode =
14439         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14440       CCode = X86::GetOppositeBranchCondition(CCode);
14441       CC = DAG.getConstant(CCode, dl, MVT::i8);
14442       Cond = Cond.getOperand(0).getOperand(1);
14443       addTest = false;
14444     } else if (Cond.getOpcode() == ISD::SETCC &&
14445                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14446       // For FCMP_OEQ, we can emit
14447       // two branches instead of an explicit AND instruction with a
14448       // separate test. However, we only do this if this block doesn't
14449       // have a fall-through edge, because this requires an explicit
14450       // jmp when the condition is false.
14451       if (Op.getNode()->hasOneUse()) {
14452         SDNode *User = *Op.getNode()->use_begin();
14453         // Look for an unconditional branch following this conditional branch.
14454         // We need this because we need to reverse the successors in order
14455         // to implement FCMP_OEQ.
14456         if (User->getOpcode() == ISD::BR) {
14457           SDValue FalseBB = User->getOperand(1);
14458           SDNode *NewBR =
14459             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14460           assert(NewBR == User);
14461           (void)NewBR;
14462           Dest = FalseBB;
14463
14464           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14465                                     Cond.getOperand(0), Cond.getOperand(1));
14466           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14467           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14468           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14469                               Chain, Dest, CC, Cmp);
14470           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14471           Cond = Cmp;
14472           addTest = false;
14473         }
14474       }
14475     } else if (Cond.getOpcode() == ISD::SETCC &&
14476                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14477       // For FCMP_UNE, we can emit
14478       // two branches instead of an explicit AND instruction with a
14479       // separate test. However, we only do this if this block doesn't
14480       // have a fall-through edge, because this requires an explicit
14481       // jmp when the condition is false.
14482       if (Op.getNode()->hasOneUse()) {
14483         SDNode *User = *Op.getNode()->use_begin();
14484         // Look for an unconditional branch following this conditional branch.
14485         // We need this because we need to reverse the successors in order
14486         // to implement FCMP_UNE.
14487         if (User->getOpcode() == ISD::BR) {
14488           SDValue FalseBB = User->getOperand(1);
14489           SDNode *NewBR =
14490             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14491           assert(NewBR == User);
14492           (void)NewBR;
14493
14494           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14495                                     Cond.getOperand(0), Cond.getOperand(1));
14496           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14497           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14498           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14499                               Chain, Dest, CC, Cmp);
14500           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14501           Cond = Cmp;
14502           addTest = false;
14503           Dest = FalseBB;
14504         }
14505       }
14506     }
14507   }
14508
14509   if (addTest) {
14510     // Look pass the truncate if the high bits are known zero.
14511     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14512         Cond = Cond.getOperand(0);
14513
14514     // We know the result of AND is compared against zero. Try to match
14515     // it to BT.
14516     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14517       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14518       if (NewSetCC.getNode()) {
14519         CC = NewSetCC.getOperand(0);
14520         Cond = NewSetCC.getOperand(1);
14521         addTest = false;
14522       }
14523     }
14524   }
14525
14526   if (addTest) {
14527     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14528     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14529     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14530   }
14531   Cond = ConvertCmpIfNecessary(Cond, DAG);
14532   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14533                      Chain, Dest, CC, Cond);
14534 }
14535
14536 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14537 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14538 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14539 // that the guard pages used by the OS virtual memory manager are allocated in
14540 // correct sequence.
14541 SDValue
14542 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14543                                            SelectionDAG &DAG) const {
14544   MachineFunction &MF = DAG.getMachineFunction();
14545   bool SplitStack = MF.shouldSplitStack();
14546   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14547                SplitStack;
14548   SDLoc dl(Op);
14549
14550   if (!Lower) {
14551     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14552     SDNode* Node = Op.getNode();
14553
14554     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14555     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14556         " not tell us which reg is the stack pointer!");
14557     EVT VT = Node->getValueType(0);
14558     SDValue Tmp1 = SDValue(Node, 0);
14559     SDValue Tmp2 = SDValue(Node, 1);
14560     SDValue Tmp3 = Node->getOperand(2);
14561     SDValue Chain = Tmp1.getOperand(0);
14562
14563     // Chain the dynamic stack allocation so that it doesn't modify the stack
14564     // pointer when other instructions are using the stack.
14565     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14566         SDLoc(Node));
14567
14568     SDValue Size = Tmp2.getOperand(1);
14569     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14570     Chain = SP.getValue(1);
14571     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14572     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14573     unsigned StackAlign = TFI.getStackAlignment();
14574     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14575     if (Align > StackAlign)
14576       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14577           DAG.getConstant(-(uint64_t)Align, dl, VT));
14578     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14579
14580     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14581         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14582         SDLoc(Node));
14583
14584     SDValue Ops[2] = { Tmp1, Tmp2 };
14585     return DAG.getMergeValues(Ops, dl);
14586   }
14587
14588   // Get the inputs.
14589   SDValue Chain = Op.getOperand(0);
14590   SDValue Size  = Op.getOperand(1);
14591   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14592   EVT VT = Op.getNode()->getValueType(0);
14593
14594   bool Is64Bit = Subtarget->is64Bit();
14595   EVT SPTy = getPointerTy();
14596
14597   if (SplitStack) {
14598     MachineRegisterInfo &MRI = MF.getRegInfo();
14599
14600     if (Is64Bit) {
14601       // The 64 bit implementation of segmented stacks needs to clobber both r10
14602       // r11. This makes it impossible to use it along with nested parameters.
14603       const Function *F = MF.getFunction();
14604
14605       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14606            I != E; ++I)
14607         if (I->hasNestAttr())
14608           report_fatal_error("Cannot use segmented stacks with functions that "
14609                              "have nested arguments.");
14610     }
14611
14612     const TargetRegisterClass *AddrRegClass =
14613       getRegClassFor(getPointerTy());
14614     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14615     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14616     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14617                                 DAG.getRegister(Vreg, SPTy));
14618     SDValue Ops1[2] = { Value, Chain };
14619     return DAG.getMergeValues(Ops1, dl);
14620   } else {
14621     SDValue Flag;
14622     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14623
14624     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14625     Flag = Chain.getValue(1);
14626     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14627
14628     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14629
14630     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14631     unsigned SPReg = RegInfo->getStackRegister();
14632     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14633     Chain = SP.getValue(1);
14634
14635     if (Align) {
14636       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14637                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14638       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14639     }
14640
14641     SDValue Ops1[2] = { SP, Chain };
14642     return DAG.getMergeValues(Ops1, dl);
14643   }
14644 }
14645
14646 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14647   MachineFunction &MF = DAG.getMachineFunction();
14648   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14649
14650   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14651   SDLoc DL(Op);
14652
14653   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14654     // vastart just stores the address of the VarArgsFrameIndex slot into the
14655     // memory location argument.
14656     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14657                                    getPointerTy());
14658     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14659                         MachinePointerInfo(SV), false, false, 0);
14660   }
14661
14662   // __va_list_tag:
14663   //   gp_offset         (0 - 6 * 8)
14664   //   fp_offset         (48 - 48 + 8 * 16)
14665   //   overflow_arg_area (point to parameters coming in memory).
14666   //   reg_save_area
14667   SmallVector<SDValue, 8> MemOps;
14668   SDValue FIN = Op.getOperand(1);
14669   // Store gp_offset
14670   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14671                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14672                                                DL, MVT::i32),
14673                                FIN, MachinePointerInfo(SV), false, false, 0);
14674   MemOps.push_back(Store);
14675
14676   // Store fp_offset
14677   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14678                     FIN, DAG.getIntPtrConstant(4, DL));
14679   Store = DAG.getStore(Op.getOperand(0), DL,
14680                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14681                                        MVT::i32),
14682                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14683   MemOps.push_back(Store);
14684
14685   // Store ptr to overflow_arg_area
14686   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14687                     FIN, DAG.getIntPtrConstant(4, DL));
14688   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14689                                     getPointerTy());
14690   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14691                        MachinePointerInfo(SV, 8),
14692                        false, false, 0);
14693   MemOps.push_back(Store);
14694
14695   // Store ptr to reg_save_area.
14696   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14697                     FIN, DAG.getIntPtrConstant(8, DL));
14698   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14699                                     getPointerTy());
14700   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14701                        MachinePointerInfo(SV, 16), false, false, 0);
14702   MemOps.push_back(Store);
14703   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14704 }
14705
14706 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14707   assert(Subtarget->is64Bit() &&
14708          "LowerVAARG only handles 64-bit va_arg!");
14709   assert((Subtarget->isTargetLinux() ||
14710           Subtarget->isTargetDarwin()) &&
14711           "Unhandled target in LowerVAARG");
14712   assert(Op.getNode()->getNumOperands() == 4);
14713   SDValue Chain = Op.getOperand(0);
14714   SDValue SrcPtr = Op.getOperand(1);
14715   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14716   unsigned Align = Op.getConstantOperandVal(3);
14717   SDLoc dl(Op);
14718
14719   EVT ArgVT = Op.getNode()->getValueType(0);
14720   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14721   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14722   uint8_t ArgMode;
14723
14724   // Decide which area this value should be read from.
14725   // TODO: Implement the AMD64 ABI in its entirety. This simple
14726   // selection mechanism works only for the basic types.
14727   if (ArgVT == MVT::f80) {
14728     llvm_unreachable("va_arg for f80 not yet implemented");
14729   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14730     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14731   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14732     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14733   } else {
14734     llvm_unreachable("Unhandled argument type in LowerVAARG");
14735   }
14736
14737   if (ArgMode == 2) {
14738     // Sanity Check: Make sure using fp_offset makes sense.
14739     assert(!Subtarget->useSoftFloat() &&
14740            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14741                Attribute::NoImplicitFloat)) &&
14742            Subtarget->hasSSE1());
14743   }
14744
14745   // Insert VAARG_64 node into the DAG
14746   // VAARG_64 returns two values: Variable Argument Address, Chain
14747   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14748                        DAG.getConstant(ArgMode, dl, MVT::i8),
14749                        DAG.getConstant(Align, dl, MVT::i32)};
14750   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14751   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14752                                           VTs, InstOps, MVT::i64,
14753                                           MachinePointerInfo(SV),
14754                                           /*Align=*/0,
14755                                           /*Volatile=*/false,
14756                                           /*ReadMem=*/true,
14757                                           /*WriteMem=*/true);
14758   Chain = VAARG.getValue(1);
14759
14760   // Load the next argument and return it
14761   return DAG.getLoad(ArgVT, dl,
14762                      Chain,
14763                      VAARG,
14764                      MachinePointerInfo(),
14765                      false, false, false, 0);
14766 }
14767
14768 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14769                            SelectionDAG &DAG) {
14770   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14771   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14772   SDValue Chain = Op.getOperand(0);
14773   SDValue DstPtr = Op.getOperand(1);
14774   SDValue SrcPtr = Op.getOperand(2);
14775   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14776   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14777   SDLoc DL(Op);
14778
14779   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14780                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14781                        false, false,
14782                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14783 }
14784
14785 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14786 // amount is a constant. Takes immediate version of shift as input.
14787 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14788                                           SDValue SrcOp, uint64_t ShiftAmt,
14789                                           SelectionDAG &DAG) {
14790   MVT ElementType = VT.getVectorElementType();
14791
14792   // Fold this packed shift into its first operand if ShiftAmt is 0.
14793   if (ShiftAmt == 0)
14794     return SrcOp;
14795
14796   // Check for ShiftAmt >= element width
14797   if (ShiftAmt >= ElementType.getSizeInBits()) {
14798     if (Opc == X86ISD::VSRAI)
14799       ShiftAmt = ElementType.getSizeInBits() - 1;
14800     else
14801       return DAG.getConstant(0, dl, VT);
14802   }
14803
14804   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14805          && "Unknown target vector shift-by-constant node");
14806
14807   // Fold this packed vector shift into a build vector if SrcOp is a
14808   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14809   if (VT == SrcOp.getSimpleValueType() &&
14810       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14811     SmallVector<SDValue, 8> Elts;
14812     unsigned NumElts = SrcOp->getNumOperands();
14813     ConstantSDNode *ND;
14814
14815     switch(Opc) {
14816     default: llvm_unreachable(nullptr);
14817     case X86ISD::VSHLI:
14818       for (unsigned i=0; i!=NumElts; ++i) {
14819         SDValue CurrentOp = SrcOp->getOperand(i);
14820         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14821           Elts.push_back(CurrentOp);
14822           continue;
14823         }
14824         ND = cast<ConstantSDNode>(CurrentOp);
14825         const APInt &C = ND->getAPIntValue();
14826         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14827       }
14828       break;
14829     case X86ISD::VSRLI:
14830       for (unsigned i=0; i!=NumElts; ++i) {
14831         SDValue CurrentOp = SrcOp->getOperand(i);
14832         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14833           Elts.push_back(CurrentOp);
14834           continue;
14835         }
14836         ND = cast<ConstantSDNode>(CurrentOp);
14837         const APInt &C = ND->getAPIntValue();
14838         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14839       }
14840       break;
14841     case X86ISD::VSRAI:
14842       for (unsigned i=0; i!=NumElts; ++i) {
14843         SDValue CurrentOp = SrcOp->getOperand(i);
14844         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14845           Elts.push_back(CurrentOp);
14846           continue;
14847         }
14848         ND = cast<ConstantSDNode>(CurrentOp);
14849         const APInt &C = ND->getAPIntValue();
14850         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14851       }
14852       break;
14853     }
14854
14855     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14856   }
14857
14858   return DAG.getNode(Opc, dl, VT, SrcOp,
14859                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14860 }
14861
14862 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14863 // may or may not be a constant. Takes immediate version of shift as input.
14864 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14865                                    SDValue SrcOp, SDValue ShAmt,
14866                                    SelectionDAG &DAG) {
14867   MVT SVT = ShAmt.getSimpleValueType();
14868   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14869
14870   // Catch shift-by-constant.
14871   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14872     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14873                                       CShAmt->getZExtValue(), DAG);
14874
14875   // Change opcode to non-immediate version
14876   switch (Opc) {
14877     default: llvm_unreachable("Unknown target vector shift node");
14878     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14879     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14880     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14881   }
14882
14883   const X86Subtarget &Subtarget =
14884       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14885   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14886       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14887     // Let the shuffle legalizer expand this shift amount node.
14888     SDValue Op0 = ShAmt.getOperand(0);
14889     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14890     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14891   } else {
14892     // Need to build a vector containing shift amount.
14893     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14894     SmallVector<SDValue, 4> ShOps;
14895     ShOps.push_back(ShAmt);
14896     if (SVT == MVT::i32) {
14897       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14898       ShOps.push_back(DAG.getUNDEF(SVT));
14899     }
14900     ShOps.push_back(DAG.getUNDEF(SVT));
14901
14902     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14903     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14904   }
14905
14906   // The return type has to be a 128-bit type with the same element
14907   // type as the input type.
14908   MVT EltVT = VT.getVectorElementType();
14909   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14910
14911   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14912   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14913 }
14914
14915 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14916 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14917 /// necessary casting for \p Mask when lowering masking intrinsics.
14918 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14919                                     SDValue PreservedSrc,
14920                                     const X86Subtarget *Subtarget,
14921                                     SelectionDAG &DAG) {
14922     EVT VT = Op.getValueType();
14923     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14924                                   MVT::i1, VT.getVectorNumElements());
14925     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14926                                      Mask.getValueType().getSizeInBits());
14927     SDLoc dl(Op);
14928
14929     assert(MaskVT.isSimple() && "invalid mask type");
14930
14931     if (isAllOnes(Mask))
14932       return Op;
14933
14934     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14935     // are extracted by EXTRACT_SUBVECTOR.
14936     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14937                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14938                               DAG.getIntPtrConstant(0, dl));
14939
14940     switch (Op.getOpcode()) {
14941       default: break;
14942       case X86ISD::PCMPEQM:
14943       case X86ISD::PCMPGTM:
14944       case X86ISD::CMPM:
14945       case X86ISD::CMPMU:
14946         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14947     }
14948     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14949       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14950     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14951 }
14952
14953 /// \brief Creates an SDNode for a predicated scalar operation.
14954 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14955 /// The mask is comming as MVT::i8 and it should be truncated
14956 /// to MVT::i1 while lowering masking intrinsics.
14957 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14958 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14959 /// a scalar instruction.
14960 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14961                                     SDValue PreservedSrc,
14962                                     const X86Subtarget *Subtarget,
14963                                     SelectionDAG &DAG) {
14964     if (isAllOnes(Mask))
14965       return Op;
14966
14967     EVT VT = Op.getValueType();
14968     SDLoc dl(Op);
14969     // The mask should be of type MVT::i1
14970     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14971
14972     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14973       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14974     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14975 }
14976
14977 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14978                                        SelectionDAG &DAG) {
14979   SDLoc dl(Op);
14980   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14981   EVT VT = Op.getValueType();
14982   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14983   if (IntrData) {
14984     switch(IntrData->Type) {
14985     case INTR_TYPE_1OP:
14986       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14987     case INTR_TYPE_2OP:
14988       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14989         Op.getOperand(2));
14990     case INTR_TYPE_3OP:
14991       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14992         Op.getOperand(2), Op.getOperand(3));
14993     case INTR_TYPE_1OP_MASK_RM: {
14994       SDValue Src = Op.getOperand(1);
14995       SDValue Src0 = Op.getOperand(2);
14996       SDValue Mask = Op.getOperand(3);
14997       SDValue RoundingMode = Op.getOperand(4);
14998       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14999                                               RoundingMode),
15000                                   Mask, Src0, Subtarget, DAG);
15001     }
15002     case INTR_TYPE_SCALAR_MASK_RM: {
15003       SDValue Src1 = Op.getOperand(1);
15004       SDValue Src2 = Op.getOperand(2);
15005       SDValue Src0 = Op.getOperand(3);
15006       SDValue Mask = Op.getOperand(4);
15007       // There are 2 kinds of intrinsics in this group:
15008       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15009       // (2) With rounding mode and sae - 7 operands.
15010       if (Op.getNumOperands() == 6) {
15011         SDValue Sae  = Op.getOperand(5);
15012         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15013         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15014                                                 Sae),
15015                                     Mask, Src0, Subtarget, DAG);
15016       }
15017       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15018       SDValue RoundingMode  = Op.getOperand(5);
15019       SDValue Sae  = Op.getOperand(6);
15020       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15021                                               RoundingMode, Sae),
15022                                   Mask, Src0, Subtarget, DAG);
15023     }
15024     case INTR_TYPE_2OP_MASK: {
15025       SDValue Src1 = Op.getOperand(1);
15026       SDValue Src2 = Op.getOperand(2);
15027       SDValue PassThru = Op.getOperand(3);
15028       SDValue Mask = Op.getOperand(4);
15029       // We specify 2 possible opcodes for intrinsics with rounding modes.
15030       // First, we check if the intrinsic may have non-default rounding mode,
15031       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15032       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15033       if (IntrWithRoundingModeOpcode != 0) {
15034         SDValue Rnd = Op.getOperand(5);
15035         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15036         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15037           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15038                                       dl, Op.getValueType(),
15039                                       Src1, Src2, Rnd),
15040                                       Mask, PassThru, Subtarget, DAG);
15041         }
15042       }
15043       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15044                                               Src1,Src2),
15045                                   Mask, PassThru, Subtarget, DAG);
15046     }
15047     case FMA_OP_MASK: {
15048       SDValue Src1 = Op.getOperand(1);
15049       SDValue Src2 = Op.getOperand(2);
15050       SDValue Src3 = Op.getOperand(3);
15051       SDValue Mask = Op.getOperand(4);
15052       // We specify 2 possible opcodes for intrinsics with rounding modes.
15053       // First, we check if the intrinsic may have non-default rounding mode,
15054       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15055       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15056       if (IntrWithRoundingModeOpcode != 0) {
15057         SDValue Rnd = Op.getOperand(5);
15058         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15059             X86::STATIC_ROUNDING::CUR_DIRECTION)
15060           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15061                                                   dl, Op.getValueType(),
15062                                                   Src1, Src2, Src3, Rnd),
15063                                       Mask, Src1, Subtarget, DAG);
15064       }
15065       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15066                                               dl, Op.getValueType(),
15067                                               Src1, Src2, Src3),
15068                                   Mask, Src1, Subtarget, DAG);
15069     }
15070     case CMP_MASK:
15071     case CMP_MASK_CC: {
15072       // Comparison intrinsics with masks.
15073       // Example of transformation:
15074       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15075       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15076       // (i8 (bitcast
15077       //   (v8i1 (insert_subvector undef,
15078       //           (v2i1 (and (PCMPEQM %a, %b),
15079       //                      (extract_subvector
15080       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15081       EVT VT = Op.getOperand(1).getValueType();
15082       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15083                                     VT.getVectorNumElements());
15084       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15085       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15086                                        Mask.getValueType().getSizeInBits());
15087       SDValue Cmp;
15088       if (IntrData->Type == CMP_MASK_CC) {
15089         SDValue CC = Op.getOperand(3);
15090         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15091         // We specify 2 possible opcodes for intrinsics with rounding modes.
15092         // First, we check if the intrinsic may have non-default rounding mode,
15093         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15094         if (IntrData->Opc1 != 0) {
15095           SDValue Rnd = Op.getOperand(5);
15096           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15097               X86::STATIC_ROUNDING::CUR_DIRECTION)
15098             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15099                               Op.getOperand(2), CC, Rnd);
15100         }
15101         //default rounding mode
15102         if(!Cmp.getNode())
15103             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15104                               Op.getOperand(2), CC);
15105
15106       } else {
15107         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15108         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15109                           Op.getOperand(2));
15110       }
15111       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15112                                              DAG.getTargetConstant(0, dl,
15113                                                                    MaskVT),
15114                                              Subtarget, DAG);
15115       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15116                                 DAG.getUNDEF(BitcastVT), CmpMask,
15117                                 DAG.getIntPtrConstant(0, dl));
15118       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15119     }
15120     case COMI: { // Comparison intrinsics
15121       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15122       SDValue LHS = Op.getOperand(1);
15123       SDValue RHS = Op.getOperand(2);
15124       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15125       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15126       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15127       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15128                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15129       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15130     }
15131     case VSHIFT:
15132       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15133                                  Op.getOperand(1), Op.getOperand(2), DAG);
15134     case VSHIFT_MASK:
15135       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15136                                                       Op.getSimpleValueType(),
15137                                                       Op.getOperand(1),
15138                                                       Op.getOperand(2), DAG),
15139                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15140                                   DAG);
15141     case COMPRESS_EXPAND_IN_REG: {
15142       SDValue Mask = Op.getOperand(3);
15143       SDValue DataToCompress = Op.getOperand(1);
15144       SDValue PassThru = Op.getOperand(2);
15145       if (isAllOnes(Mask)) // return data as is
15146         return Op.getOperand(1);
15147       EVT VT = Op.getValueType();
15148       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15149                                     VT.getVectorNumElements());
15150       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15151                                        Mask.getValueType().getSizeInBits());
15152       SDLoc dl(Op);
15153       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15154                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15155                                   DAG.getIntPtrConstant(0, dl));
15156
15157       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15158                          PassThru);
15159     }
15160     case BLEND: {
15161       SDValue Mask = Op.getOperand(3);
15162       EVT VT = Op.getValueType();
15163       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15164                                     VT.getVectorNumElements());
15165       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15166                                        Mask.getValueType().getSizeInBits());
15167       SDLoc dl(Op);
15168       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15169                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15170                                   DAG.getIntPtrConstant(0, dl));
15171       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15172                          Op.getOperand(2));
15173     }
15174     default:
15175       break;
15176     }
15177   }
15178
15179   switch (IntNo) {
15180   default: return SDValue();    // Don't custom lower most intrinsics.
15181
15182   case Intrinsic::x86_avx2_permd:
15183   case Intrinsic::x86_avx2_permps:
15184     // Operands intentionally swapped. Mask is last operand to intrinsic,
15185     // but second operand for node/instruction.
15186     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15187                        Op.getOperand(2), Op.getOperand(1));
15188
15189   case Intrinsic::x86_avx512_mask_valign_q_512:
15190   case Intrinsic::x86_avx512_mask_valign_d_512:
15191     // Vector source operands are swapped.
15192     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15193                                             Op.getValueType(), Op.getOperand(2),
15194                                             Op.getOperand(1),
15195                                             Op.getOperand(3)),
15196                                 Op.getOperand(5), Op.getOperand(4),
15197                                 Subtarget, DAG);
15198
15199   // ptest and testp intrinsics. The intrinsic these come from are designed to
15200   // return an integer value, not just an instruction so lower it to the ptest
15201   // or testp pattern and a setcc for the result.
15202   case Intrinsic::x86_sse41_ptestz:
15203   case Intrinsic::x86_sse41_ptestc:
15204   case Intrinsic::x86_sse41_ptestnzc:
15205   case Intrinsic::x86_avx_ptestz_256:
15206   case Intrinsic::x86_avx_ptestc_256:
15207   case Intrinsic::x86_avx_ptestnzc_256:
15208   case Intrinsic::x86_avx_vtestz_ps:
15209   case Intrinsic::x86_avx_vtestc_ps:
15210   case Intrinsic::x86_avx_vtestnzc_ps:
15211   case Intrinsic::x86_avx_vtestz_pd:
15212   case Intrinsic::x86_avx_vtestc_pd:
15213   case Intrinsic::x86_avx_vtestnzc_pd:
15214   case Intrinsic::x86_avx_vtestz_ps_256:
15215   case Intrinsic::x86_avx_vtestc_ps_256:
15216   case Intrinsic::x86_avx_vtestnzc_ps_256:
15217   case Intrinsic::x86_avx_vtestz_pd_256:
15218   case Intrinsic::x86_avx_vtestc_pd_256:
15219   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15220     bool IsTestPacked = false;
15221     unsigned X86CC;
15222     switch (IntNo) {
15223     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15224     case Intrinsic::x86_avx_vtestz_ps:
15225     case Intrinsic::x86_avx_vtestz_pd:
15226     case Intrinsic::x86_avx_vtestz_ps_256:
15227     case Intrinsic::x86_avx_vtestz_pd_256:
15228       IsTestPacked = true; // Fallthrough
15229     case Intrinsic::x86_sse41_ptestz:
15230     case Intrinsic::x86_avx_ptestz_256:
15231       // ZF = 1
15232       X86CC = X86::COND_E;
15233       break;
15234     case Intrinsic::x86_avx_vtestc_ps:
15235     case Intrinsic::x86_avx_vtestc_pd:
15236     case Intrinsic::x86_avx_vtestc_ps_256:
15237     case Intrinsic::x86_avx_vtestc_pd_256:
15238       IsTestPacked = true; // Fallthrough
15239     case Intrinsic::x86_sse41_ptestc:
15240     case Intrinsic::x86_avx_ptestc_256:
15241       // CF = 1
15242       X86CC = X86::COND_B;
15243       break;
15244     case Intrinsic::x86_avx_vtestnzc_ps:
15245     case Intrinsic::x86_avx_vtestnzc_pd:
15246     case Intrinsic::x86_avx_vtestnzc_ps_256:
15247     case Intrinsic::x86_avx_vtestnzc_pd_256:
15248       IsTestPacked = true; // Fallthrough
15249     case Intrinsic::x86_sse41_ptestnzc:
15250     case Intrinsic::x86_avx_ptestnzc_256:
15251       // ZF and CF = 0
15252       X86CC = X86::COND_A;
15253       break;
15254     }
15255
15256     SDValue LHS = Op.getOperand(1);
15257     SDValue RHS = Op.getOperand(2);
15258     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15259     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15260     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15261     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15262     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15263   }
15264   case Intrinsic::x86_avx512_kortestz_w:
15265   case Intrinsic::x86_avx512_kortestc_w: {
15266     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15267     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15268     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15269     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15270     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15271     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15272     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15273   }
15274
15275   case Intrinsic::x86_sse42_pcmpistria128:
15276   case Intrinsic::x86_sse42_pcmpestria128:
15277   case Intrinsic::x86_sse42_pcmpistric128:
15278   case Intrinsic::x86_sse42_pcmpestric128:
15279   case Intrinsic::x86_sse42_pcmpistrio128:
15280   case Intrinsic::x86_sse42_pcmpestrio128:
15281   case Intrinsic::x86_sse42_pcmpistris128:
15282   case Intrinsic::x86_sse42_pcmpestris128:
15283   case Intrinsic::x86_sse42_pcmpistriz128:
15284   case Intrinsic::x86_sse42_pcmpestriz128: {
15285     unsigned Opcode;
15286     unsigned X86CC;
15287     switch (IntNo) {
15288     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15289     case Intrinsic::x86_sse42_pcmpistria128:
15290       Opcode = X86ISD::PCMPISTRI;
15291       X86CC = X86::COND_A;
15292       break;
15293     case Intrinsic::x86_sse42_pcmpestria128:
15294       Opcode = X86ISD::PCMPESTRI;
15295       X86CC = X86::COND_A;
15296       break;
15297     case Intrinsic::x86_sse42_pcmpistric128:
15298       Opcode = X86ISD::PCMPISTRI;
15299       X86CC = X86::COND_B;
15300       break;
15301     case Intrinsic::x86_sse42_pcmpestric128:
15302       Opcode = X86ISD::PCMPESTRI;
15303       X86CC = X86::COND_B;
15304       break;
15305     case Intrinsic::x86_sse42_pcmpistrio128:
15306       Opcode = X86ISD::PCMPISTRI;
15307       X86CC = X86::COND_O;
15308       break;
15309     case Intrinsic::x86_sse42_pcmpestrio128:
15310       Opcode = X86ISD::PCMPESTRI;
15311       X86CC = X86::COND_O;
15312       break;
15313     case Intrinsic::x86_sse42_pcmpistris128:
15314       Opcode = X86ISD::PCMPISTRI;
15315       X86CC = X86::COND_S;
15316       break;
15317     case Intrinsic::x86_sse42_pcmpestris128:
15318       Opcode = X86ISD::PCMPESTRI;
15319       X86CC = X86::COND_S;
15320       break;
15321     case Intrinsic::x86_sse42_pcmpistriz128:
15322       Opcode = X86ISD::PCMPISTRI;
15323       X86CC = X86::COND_E;
15324       break;
15325     case Intrinsic::x86_sse42_pcmpestriz128:
15326       Opcode = X86ISD::PCMPESTRI;
15327       X86CC = X86::COND_E;
15328       break;
15329     }
15330     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15331     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15332     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15333     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15334                                 DAG.getConstant(X86CC, dl, MVT::i8),
15335                                 SDValue(PCMP.getNode(), 1));
15336     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15337   }
15338
15339   case Intrinsic::x86_sse42_pcmpistri128:
15340   case Intrinsic::x86_sse42_pcmpestri128: {
15341     unsigned Opcode;
15342     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15343       Opcode = X86ISD::PCMPISTRI;
15344     else
15345       Opcode = X86ISD::PCMPESTRI;
15346
15347     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15348     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15349     return DAG.getNode(Opcode, dl, VTs, NewOps);
15350   }
15351
15352   case Intrinsic::x86_seh_lsda: {
15353     // Compute the symbol for the LSDA. We know it'll get emitted later.
15354     MachineFunction &MF = DAG.getMachineFunction();
15355     SDValue Op1 = Op.getOperand(1);
15356     Op1->dump();
15357     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15358     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15359         GlobalValue::getRealLinkageName(Fn->getName()));
15360     StringRef Name = LSDASym->getName();
15361     assert(Name.data()[Name.size()] == '\0' && "not null terminated");
15362
15363     // Generate a simple absolute symbol reference. This intrinsic is only
15364     // supported on 32-bit Windows, which isn't PIC.
15365     SDValue Result =
15366         DAG.getTargetExternalSymbol(Name.data(), VT, X86II::MO_NOPREFIX);
15367     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15368   }
15369   }
15370 }
15371
15372 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15373                               SDValue Src, SDValue Mask, SDValue Base,
15374                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15375                               const X86Subtarget * Subtarget) {
15376   SDLoc dl(Op);
15377   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15378   assert(C && "Invalid scale type");
15379   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15380   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15381                              Index.getSimpleValueType().getVectorNumElements());
15382   SDValue MaskInReg;
15383   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15384   if (MaskC)
15385     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15386   else
15387     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15388   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15389   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15390   SDValue Segment = DAG.getRegister(0, MVT::i32);
15391   if (Src.getOpcode() == ISD::UNDEF)
15392     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15393   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15394   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15395   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15396   return DAG.getMergeValues(RetOps, dl);
15397 }
15398
15399 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15400                                SDValue Src, SDValue Mask, SDValue Base,
15401                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15402   SDLoc dl(Op);
15403   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15404   assert(C && "Invalid scale type");
15405   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15406   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15407   SDValue Segment = DAG.getRegister(0, MVT::i32);
15408   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15409                              Index.getSimpleValueType().getVectorNumElements());
15410   SDValue MaskInReg;
15411   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15412   if (MaskC)
15413     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15414   else
15415     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15416   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15417   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15418   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15419   return SDValue(Res, 1);
15420 }
15421
15422 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15423                                SDValue Mask, SDValue Base, SDValue Index,
15424                                SDValue ScaleOp, SDValue Chain) {
15425   SDLoc dl(Op);
15426   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15427   assert(C && "Invalid scale type");
15428   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15429   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15430   SDValue Segment = DAG.getRegister(0, MVT::i32);
15431   EVT MaskVT =
15432     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15433   SDValue MaskInReg;
15434   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15435   if (MaskC)
15436     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15437   else
15438     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15439   //SDVTList VTs = DAG.getVTList(MVT::Other);
15440   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15441   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15442   return SDValue(Res, 0);
15443 }
15444
15445 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15446 // read performance monitor counters (x86_rdpmc).
15447 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15448                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15449                               SmallVectorImpl<SDValue> &Results) {
15450   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15451   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15452   SDValue LO, HI;
15453
15454   // The ECX register is used to select the index of the performance counter
15455   // to read.
15456   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15457                                    N->getOperand(2));
15458   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15459
15460   // Reads the content of a 64-bit performance counter and returns it in the
15461   // registers EDX:EAX.
15462   if (Subtarget->is64Bit()) {
15463     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15464     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15465                             LO.getValue(2));
15466   } else {
15467     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15468     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15469                             LO.getValue(2));
15470   }
15471   Chain = HI.getValue(1);
15472
15473   if (Subtarget->is64Bit()) {
15474     // The EAX register is loaded with the low-order 32 bits. The EDX register
15475     // is loaded with the supported high-order bits of the counter.
15476     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15477                               DAG.getConstant(32, DL, MVT::i8));
15478     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15479     Results.push_back(Chain);
15480     return;
15481   }
15482
15483   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15484   SDValue Ops[] = { LO, HI };
15485   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15486   Results.push_back(Pair);
15487   Results.push_back(Chain);
15488 }
15489
15490 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15491 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15492 // also used to custom lower READCYCLECOUNTER nodes.
15493 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15494                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15495                               SmallVectorImpl<SDValue> &Results) {
15496   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15497   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15498   SDValue LO, HI;
15499
15500   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15501   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15502   // and the EAX register is loaded with the low-order 32 bits.
15503   if (Subtarget->is64Bit()) {
15504     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15505     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15506                             LO.getValue(2));
15507   } else {
15508     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15509     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15510                             LO.getValue(2));
15511   }
15512   SDValue Chain = HI.getValue(1);
15513
15514   if (Opcode == X86ISD::RDTSCP_DAG) {
15515     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15516
15517     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15518     // the ECX register. Add 'ecx' explicitly to the chain.
15519     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15520                                      HI.getValue(2));
15521     // Explicitly store the content of ECX at the location passed in input
15522     // to the 'rdtscp' intrinsic.
15523     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15524                          MachinePointerInfo(), false, false, 0);
15525   }
15526
15527   if (Subtarget->is64Bit()) {
15528     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15529     // the EAX register is loaded with the low-order 32 bits.
15530     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15531                               DAG.getConstant(32, DL, MVT::i8));
15532     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15533     Results.push_back(Chain);
15534     return;
15535   }
15536
15537   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15538   SDValue Ops[] = { LO, HI };
15539   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15540   Results.push_back(Pair);
15541   Results.push_back(Chain);
15542 }
15543
15544 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15545                                      SelectionDAG &DAG) {
15546   SmallVector<SDValue, 2> Results;
15547   SDLoc DL(Op);
15548   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15549                           Results);
15550   return DAG.getMergeValues(Results, DL);
15551 }
15552
15553
15554 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15555                                       SelectionDAG &DAG) {
15556   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15557
15558   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15559   if (!IntrData)
15560     return SDValue();
15561
15562   SDLoc dl(Op);
15563   switch(IntrData->Type) {
15564   default:
15565     llvm_unreachable("Unknown Intrinsic Type");
15566     break;
15567   case RDSEED:
15568   case RDRAND: {
15569     // Emit the node with the right value type.
15570     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15571     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15572
15573     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15574     // Otherwise return the value from Rand, which is always 0, casted to i32.
15575     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15576                       DAG.getConstant(1, dl, Op->getValueType(1)),
15577                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15578                       SDValue(Result.getNode(), 1) };
15579     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15580                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15581                                   Ops);
15582
15583     // Return { result, isValid, chain }.
15584     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15585                        SDValue(Result.getNode(), 2));
15586   }
15587   case GATHER: {
15588   //gather(v1, mask, index, base, scale);
15589     SDValue Chain = Op.getOperand(0);
15590     SDValue Src   = Op.getOperand(2);
15591     SDValue Base  = Op.getOperand(3);
15592     SDValue Index = Op.getOperand(4);
15593     SDValue Mask  = Op.getOperand(5);
15594     SDValue Scale = Op.getOperand(6);
15595     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15596                          Chain, Subtarget);
15597   }
15598   case SCATTER: {
15599   //scatter(base, mask, index, v1, scale);
15600     SDValue Chain = Op.getOperand(0);
15601     SDValue Base  = Op.getOperand(2);
15602     SDValue Mask  = Op.getOperand(3);
15603     SDValue Index = Op.getOperand(4);
15604     SDValue Src   = Op.getOperand(5);
15605     SDValue Scale = Op.getOperand(6);
15606     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15607                           Scale, Chain);
15608   }
15609   case PREFETCH: {
15610     SDValue Hint = Op.getOperand(6);
15611     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15612     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15613     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15614     SDValue Chain = Op.getOperand(0);
15615     SDValue Mask  = Op.getOperand(2);
15616     SDValue Index = Op.getOperand(3);
15617     SDValue Base  = Op.getOperand(4);
15618     SDValue Scale = Op.getOperand(5);
15619     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15620   }
15621   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15622   case RDTSC: {
15623     SmallVector<SDValue, 2> Results;
15624     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15625                             Results);
15626     return DAG.getMergeValues(Results, dl);
15627   }
15628   // Read Performance Monitoring Counters.
15629   case RDPMC: {
15630     SmallVector<SDValue, 2> Results;
15631     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15632     return DAG.getMergeValues(Results, dl);
15633   }
15634   // XTEST intrinsics.
15635   case XTEST: {
15636     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15637     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15638     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15639                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15640                                 InTrans);
15641     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15642     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15643                        Ret, SDValue(InTrans.getNode(), 1));
15644   }
15645   // ADC/ADCX/SBB
15646   case ADX: {
15647     SmallVector<SDValue, 2> Results;
15648     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15649     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15650     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15651                                 DAG.getConstant(-1, dl, MVT::i8));
15652     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15653                               Op.getOperand(4), GenCF.getValue(1));
15654     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15655                                  Op.getOperand(5), MachinePointerInfo(),
15656                                  false, false, 0);
15657     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15658                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15659                                 Res.getValue(1));
15660     Results.push_back(SetCC);
15661     Results.push_back(Store);
15662     return DAG.getMergeValues(Results, dl);
15663   }
15664   case COMPRESS_TO_MEM: {
15665     SDLoc dl(Op);
15666     SDValue Mask = Op.getOperand(4);
15667     SDValue DataToCompress = Op.getOperand(3);
15668     SDValue Addr = Op.getOperand(2);
15669     SDValue Chain = Op.getOperand(0);
15670
15671     if (isAllOnes(Mask)) // return just a store
15672       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15673                           MachinePointerInfo(), false, false, 0);
15674
15675     EVT VT = DataToCompress.getValueType();
15676     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15677                                   VT.getVectorNumElements());
15678     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15679                                      Mask.getValueType().getSizeInBits());
15680     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15681                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15682                                 DAG.getIntPtrConstant(0, dl));
15683
15684     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15685                                       DataToCompress, DAG.getUNDEF(VT));
15686     return DAG.getStore(Chain, dl, Compressed, Addr,
15687                         MachinePointerInfo(), false, false, 0);
15688   }
15689   case EXPAND_FROM_MEM: {
15690     SDLoc dl(Op);
15691     SDValue Mask = Op.getOperand(4);
15692     SDValue PathThru = Op.getOperand(3);
15693     SDValue Addr = Op.getOperand(2);
15694     SDValue Chain = Op.getOperand(0);
15695     EVT VT = Op.getValueType();
15696
15697     if (isAllOnes(Mask)) // return just a load
15698       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15699                          false, 0);
15700     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15701                                   VT.getVectorNumElements());
15702     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15703                                      Mask.getValueType().getSizeInBits());
15704     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15705                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15706                                 DAG.getIntPtrConstant(0, dl));
15707
15708     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15709                                    false, false, false, 0);
15710
15711     SDValue Results[] = {
15712         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15713         Chain};
15714     return DAG.getMergeValues(Results, dl);
15715   }
15716   }
15717 }
15718
15719 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15720                                            SelectionDAG &DAG) const {
15721   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15722   MFI->setReturnAddressIsTaken(true);
15723
15724   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15725     return SDValue();
15726
15727   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15728   SDLoc dl(Op);
15729   EVT PtrVT = getPointerTy();
15730
15731   if (Depth > 0) {
15732     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15733     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15734     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15735     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15736                        DAG.getNode(ISD::ADD, dl, PtrVT,
15737                                    FrameAddr, Offset),
15738                        MachinePointerInfo(), false, false, false, 0);
15739   }
15740
15741   // Just load the return address.
15742   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15743   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15744                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15745 }
15746
15747 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15748   MachineFunction &MF = DAG.getMachineFunction();
15749   MachineFrameInfo *MFI = MF.getFrameInfo();
15750   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15751   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15752   EVT VT = Op.getValueType();
15753
15754   MFI->setFrameAddressIsTaken(true);
15755
15756   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15757     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15758     // is not possible to crawl up the stack without looking at the unwind codes
15759     // simultaneously.
15760     int FrameAddrIndex = FuncInfo->getFAIndex();
15761     if (!FrameAddrIndex) {
15762       // Set up a frame object for the return address.
15763       unsigned SlotSize = RegInfo->getSlotSize();
15764       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15765           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
15766       FuncInfo->setFAIndex(FrameAddrIndex);
15767     }
15768     return DAG.getFrameIndex(FrameAddrIndex, VT);
15769   }
15770
15771   unsigned FrameReg =
15772       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15773   SDLoc dl(Op);  // FIXME probably not meaningful
15774   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15775   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15776           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15777          "Invalid Frame Register!");
15778   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15779   while (Depth--)
15780     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15781                             MachinePointerInfo(),
15782                             false, false, false, 0);
15783   return FrameAddr;
15784 }
15785
15786 // FIXME? Maybe this could be a TableGen attribute on some registers and
15787 // this table could be generated automatically from RegInfo.
15788 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15789                                               EVT VT) const {
15790   unsigned Reg = StringSwitch<unsigned>(RegName)
15791                        .Case("esp", X86::ESP)
15792                        .Case("rsp", X86::RSP)
15793                        .Default(0);
15794   if (Reg)
15795     return Reg;
15796   report_fatal_error("Invalid register name global variable");
15797 }
15798
15799 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15800                                                      SelectionDAG &DAG) const {
15801   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15802   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15803 }
15804
15805 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15806   SDValue Chain     = Op.getOperand(0);
15807   SDValue Offset    = Op.getOperand(1);
15808   SDValue Handler   = Op.getOperand(2);
15809   SDLoc dl      (Op);
15810
15811   EVT PtrVT = getPointerTy();
15812   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15813   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15814   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15815           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15816          "Invalid Frame Register!");
15817   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15818   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15819
15820   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15821                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15822                                                        dl));
15823   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15824   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15825                        false, false, 0);
15826   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15827
15828   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15829                      DAG.getRegister(StoreAddrReg, PtrVT));
15830 }
15831
15832 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15833                                                SelectionDAG &DAG) const {
15834   SDLoc DL(Op);
15835   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15836                      DAG.getVTList(MVT::i32, MVT::Other),
15837                      Op.getOperand(0), Op.getOperand(1));
15838 }
15839
15840 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15841                                                 SelectionDAG &DAG) const {
15842   SDLoc DL(Op);
15843   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15844                      Op.getOperand(0), Op.getOperand(1));
15845 }
15846
15847 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15848   return Op.getOperand(0);
15849 }
15850
15851 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15852                                                 SelectionDAG &DAG) const {
15853   SDValue Root = Op.getOperand(0);
15854   SDValue Trmp = Op.getOperand(1); // trampoline
15855   SDValue FPtr = Op.getOperand(2); // nested function
15856   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15857   SDLoc dl (Op);
15858
15859   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15860   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15861
15862   if (Subtarget->is64Bit()) {
15863     SDValue OutChains[6];
15864
15865     // Large code-model.
15866     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15867     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15868
15869     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15870     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15871
15872     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15873
15874     // Load the pointer to the nested function into R11.
15875     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15876     SDValue Addr = Trmp;
15877     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15878                                 Addr, MachinePointerInfo(TrmpAddr),
15879                                 false, false, 0);
15880
15881     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15882                        DAG.getConstant(2, dl, MVT::i64));
15883     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15884                                 MachinePointerInfo(TrmpAddr, 2),
15885                                 false, false, 2);
15886
15887     // Load the 'nest' parameter value into R10.
15888     // R10 is specified in X86CallingConv.td
15889     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15890     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15891                        DAG.getConstant(10, dl, MVT::i64));
15892     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15893                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15894                                 false, false, 0);
15895
15896     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15897                        DAG.getConstant(12, dl, MVT::i64));
15898     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15899                                 MachinePointerInfo(TrmpAddr, 12),
15900                                 false, false, 2);
15901
15902     // Jump to the nested function.
15903     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15904     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15905                        DAG.getConstant(20, dl, MVT::i64));
15906     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15907                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15908                                 false, false, 0);
15909
15910     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15911     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15912                        DAG.getConstant(22, dl, MVT::i64));
15913     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15914                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15915                                 false, false, 0);
15916
15917     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15918   } else {
15919     const Function *Func =
15920       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15921     CallingConv::ID CC = Func->getCallingConv();
15922     unsigned NestReg;
15923
15924     switch (CC) {
15925     default:
15926       llvm_unreachable("Unsupported calling convention");
15927     case CallingConv::C:
15928     case CallingConv::X86_StdCall: {
15929       // Pass 'nest' parameter in ECX.
15930       // Must be kept in sync with X86CallingConv.td
15931       NestReg = X86::ECX;
15932
15933       // Check that ECX wasn't needed by an 'inreg' parameter.
15934       FunctionType *FTy = Func->getFunctionType();
15935       const AttributeSet &Attrs = Func->getAttributes();
15936
15937       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15938         unsigned InRegCount = 0;
15939         unsigned Idx = 1;
15940
15941         for (FunctionType::param_iterator I = FTy->param_begin(),
15942              E = FTy->param_end(); I != E; ++I, ++Idx)
15943           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15944             // FIXME: should only count parameters that are lowered to integers.
15945             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15946
15947         if (InRegCount > 2) {
15948           report_fatal_error("Nest register in use - reduce number of inreg"
15949                              " parameters!");
15950         }
15951       }
15952       break;
15953     }
15954     case CallingConv::X86_FastCall:
15955     case CallingConv::X86_ThisCall:
15956     case CallingConv::Fast:
15957       // Pass 'nest' parameter in EAX.
15958       // Must be kept in sync with X86CallingConv.td
15959       NestReg = X86::EAX;
15960       break;
15961     }
15962
15963     SDValue OutChains[4];
15964     SDValue Addr, Disp;
15965
15966     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15967                        DAG.getConstant(10, dl, MVT::i32));
15968     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15969
15970     // This is storing the opcode for MOV32ri.
15971     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15972     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15973     OutChains[0] = DAG.getStore(Root, dl,
15974                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15975                                 Trmp, MachinePointerInfo(TrmpAddr),
15976                                 false, false, 0);
15977
15978     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15979                        DAG.getConstant(1, dl, MVT::i32));
15980     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15981                                 MachinePointerInfo(TrmpAddr, 1),
15982                                 false, false, 1);
15983
15984     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15985     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15986                        DAG.getConstant(5, dl, MVT::i32));
15987     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15988                                 Addr, MachinePointerInfo(TrmpAddr, 5),
15989                                 false, false, 1);
15990
15991     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15992                        DAG.getConstant(6, dl, MVT::i32));
15993     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15994                                 MachinePointerInfo(TrmpAddr, 6),
15995                                 false, false, 1);
15996
15997     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15998   }
15999 }
16000
16001 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16002                                             SelectionDAG &DAG) const {
16003   /*
16004    The rounding mode is in bits 11:10 of FPSR, and has the following
16005    settings:
16006      00 Round to nearest
16007      01 Round to -inf
16008      10 Round to +inf
16009      11 Round to 0
16010
16011   FLT_ROUNDS, on the other hand, expects the following:
16012     -1 Undefined
16013      0 Round to 0
16014      1 Round to nearest
16015      2 Round to +inf
16016      3 Round to -inf
16017
16018   To perform the conversion, we do:
16019     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16020   */
16021
16022   MachineFunction &MF = DAG.getMachineFunction();
16023   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16024   unsigned StackAlignment = TFI.getStackAlignment();
16025   MVT VT = Op.getSimpleValueType();
16026   SDLoc DL(Op);
16027
16028   // Save FP Control Word to stack slot
16029   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16030   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16031
16032   MachineMemOperand *MMO =
16033    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16034                            MachineMemOperand::MOStore, 2, 2);
16035
16036   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16037   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16038                                           DAG.getVTList(MVT::Other),
16039                                           Ops, MVT::i16, MMO);
16040
16041   // Load FP Control Word from stack slot
16042   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16043                             MachinePointerInfo(), false, false, false, 0);
16044
16045   // Transform as necessary
16046   SDValue CWD1 =
16047     DAG.getNode(ISD::SRL, DL, MVT::i16,
16048                 DAG.getNode(ISD::AND, DL, MVT::i16,
16049                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16050                 DAG.getConstant(11, DL, MVT::i8));
16051   SDValue CWD2 =
16052     DAG.getNode(ISD::SRL, DL, MVT::i16,
16053                 DAG.getNode(ISD::AND, DL, MVT::i16,
16054                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16055                 DAG.getConstant(9, DL, MVT::i8));
16056
16057   SDValue RetVal =
16058     DAG.getNode(ISD::AND, DL, MVT::i16,
16059                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16060                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16061                             DAG.getConstant(1, DL, MVT::i16)),
16062                 DAG.getConstant(3, DL, MVT::i16));
16063
16064   return DAG.getNode((VT.getSizeInBits() < 16 ?
16065                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16066 }
16067
16068 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16069   MVT VT = Op.getSimpleValueType();
16070   EVT OpVT = VT;
16071   unsigned NumBits = VT.getSizeInBits();
16072   SDLoc dl(Op);
16073
16074   Op = Op.getOperand(0);
16075   if (VT == MVT::i8) {
16076     // Zero extend to i32 since there is not an i8 bsr.
16077     OpVT = MVT::i32;
16078     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16079   }
16080
16081   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16082   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16083   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16084
16085   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16086   SDValue Ops[] = {
16087     Op,
16088     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16089     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16090     Op.getValue(1)
16091   };
16092   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16093
16094   // Finally xor with NumBits-1.
16095   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16096                    DAG.getConstant(NumBits - 1, dl, OpVT));
16097
16098   if (VT == MVT::i8)
16099     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16100   return Op;
16101 }
16102
16103 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16104   MVT VT = Op.getSimpleValueType();
16105   EVT OpVT = VT;
16106   unsigned NumBits = VT.getSizeInBits();
16107   SDLoc dl(Op);
16108
16109   Op = Op.getOperand(0);
16110   if (VT == MVT::i8) {
16111     // Zero extend to i32 since there is not an i8 bsr.
16112     OpVT = MVT::i32;
16113     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16114   }
16115
16116   // Issue a bsr (scan bits in reverse).
16117   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16118   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16119
16120   // And xor with NumBits-1.
16121   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16122                    DAG.getConstant(NumBits - 1, dl, OpVT));
16123
16124   if (VT == MVT::i8)
16125     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16126   return Op;
16127 }
16128
16129 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16130   MVT VT = Op.getSimpleValueType();
16131   unsigned NumBits = VT.getSizeInBits();
16132   SDLoc dl(Op);
16133   Op = Op.getOperand(0);
16134
16135   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16136   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16137   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16138
16139   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16140   SDValue Ops[] = {
16141     Op,
16142     DAG.getConstant(NumBits, dl, VT),
16143     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16144     Op.getValue(1)
16145   };
16146   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16147 }
16148
16149 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16150 // ones, and then concatenate the result back.
16151 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16152   MVT VT = Op.getSimpleValueType();
16153
16154   assert(VT.is256BitVector() && VT.isInteger() &&
16155          "Unsupported value type for operation");
16156
16157   unsigned NumElems = VT.getVectorNumElements();
16158   SDLoc dl(Op);
16159
16160   // Extract the LHS vectors
16161   SDValue LHS = Op.getOperand(0);
16162   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16163   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16164
16165   // Extract the RHS vectors
16166   SDValue RHS = Op.getOperand(1);
16167   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16168   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16169
16170   MVT EltVT = VT.getVectorElementType();
16171   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16172
16173   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16174                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16175                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16176 }
16177
16178 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16179   assert(Op.getSimpleValueType().is256BitVector() &&
16180          Op.getSimpleValueType().isInteger() &&
16181          "Only handle AVX 256-bit vector integer operation");
16182   return Lower256IntArith(Op, DAG);
16183 }
16184
16185 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16186   assert(Op.getSimpleValueType().is256BitVector() &&
16187          Op.getSimpleValueType().isInteger() &&
16188          "Only handle AVX 256-bit vector integer operation");
16189   return Lower256IntArith(Op, DAG);
16190 }
16191
16192 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16193                         SelectionDAG &DAG) {
16194   SDLoc dl(Op);
16195   MVT VT = Op.getSimpleValueType();
16196
16197   // Decompose 256-bit ops into smaller 128-bit ops.
16198   if (VT.is256BitVector() && !Subtarget->hasInt256())
16199     return Lower256IntArith(Op, DAG);
16200
16201   SDValue A = Op.getOperand(0);
16202   SDValue B = Op.getOperand(1);
16203
16204   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16205   // pairs, multiply and truncate.
16206   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16207     if (Subtarget->hasInt256()) {
16208       if (VT == MVT::v32i8) {
16209         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16210         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16211         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16212         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16213         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16214         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16215         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16216         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16217                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16218                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16219       }
16220
16221       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16222       return DAG.getNode(
16223           ISD::TRUNCATE, dl, VT,
16224           DAG.getNode(ISD::MUL, dl, ExVT,
16225                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16226                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16227     }
16228
16229     assert(VT == MVT::v16i8 &&
16230            "Pre-AVX2 support only supports v16i8 multiplication");
16231     MVT ExVT = MVT::v8i16;
16232
16233     // Extract the lo parts and sign extend to i16
16234     SDValue ALo, BLo;
16235     if (Subtarget->hasSSE41()) {
16236       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16237       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16238     } else {
16239       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16240                               -1, 4, -1, 5, -1, 6, -1, 7};
16241       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16242       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16243       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16244       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16245       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16246       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16247     }
16248
16249     // Extract the hi parts and sign extend to i16
16250     SDValue AHi, BHi;
16251     if (Subtarget->hasSSE41()) {
16252       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16253                               -1, -1, -1, -1, -1, -1, -1, -1};
16254       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16255       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16256       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16257       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16258     } else {
16259       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16260                               -1, 12, -1, 13, -1, 14, -1, 15};
16261       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16262       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16263       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16264       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16265       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16266       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16267     }
16268
16269     // Multiply, mask the lower 8bits of the lo/hi results and pack
16270     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16271     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16272     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16273     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16274     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16275   }
16276
16277   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16278   if (VT == MVT::v4i32) {
16279     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16280            "Should not custom lower when pmuldq is available!");
16281
16282     // Extract the odd parts.
16283     static const int UnpackMask[] = { 1, -1, 3, -1 };
16284     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16285     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16286
16287     // Multiply the even parts.
16288     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16289     // Now multiply odd parts.
16290     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16291
16292     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16293     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16294
16295     // Merge the two vectors back together with a shuffle. This expands into 2
16296     // shuffles.
16297     static const int ShufMask[] = { 0, 4, 2, 6 };
16298     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16299   }
16300
16301   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16302          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16303
16304   //  Ahi = psrlqi(a, 32);
16305   //  Bhi = psrlqi(b, 32);
16306   //
16307   //  AloBlo = pmuludq(a, b);
16308   //  AloBhi = pmuludq(a, Bhi);
16309   //  AhiBlo = pmuludq(Ahi, b);
16310
16311   //  AloBhi = psllqi(AloBhi, 32);
16312   //  AhiBlo = psllqi(AhiBlo, 32);
16313   //  return AloBlo + AloBhi + AhiBlo;
16314
16315   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16316   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16317
16318   // Bit cast to 32-bit vectors for MULUDQ
16319   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16320                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16321   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16322   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16323   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16324   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16325
16326   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16327   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16328   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16329
16330   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16331   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16332
16333   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16334   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16335 }
16336
16337 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16338   assert(Subtarget->isTargetWin64() && "Unexpected target");
16339   EVT VT = Op.getValueType();
16340   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16341          "Unexpected return type for lowering");
16342
16343   RTLIB::Libcall LC;
16344   bool isSigned;
16345   switch (Op->getOpcode()) {
16346   default: llvm_unreachable("Unexpected request for libcall!");
16347   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16348   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16349   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16350   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16351   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16352   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16353   }
16354
16355   SDLoc dl(Op);
16356   SDValue InChain = DAG.getEntryNode();
16357
16358   TargetLowering::ArgListTy Args;
16359   TargetLowering::ArgListEntry Entry;
16360   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16361     EVT ArgVT = Op->getOperand(i).getValueType();
16362     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16363            "Unexpected argument type for lowering");
16364     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16365     Entry.Node = StackPtr;
16366     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16367                            false, false, 16);
16368     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16369     Entry.Ty = PointerType::get(ArgTy,0);
16370     Entry.isSExt = false;
16371     Entry.isZExt = false;
16372     Args.push_back(Entry);
16373   }
16374
16375   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16376                                          getPointerTy());
16377
16378   TargetLowering::CallLoweringInfo CLI(DAG);
16379   CLI.setDebugLoc(dl).setChain(InChain)
16380     .setCallee(getLibcallCallingConv(LC),
16381                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16382                Callee, std::move(Args), 0)
16383     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16384
16385   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16386   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16387 }
16388
16389 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16390                              SelectionDAG &DAG) {
16391   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16392   EVT VT = Op0.getValueType();
16393   SDLoc dl(Op);
16394
16395   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16396          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16397
16398   // PMULxD operations multiply each even value (starting at 0) of LHS with
16399   // the related value of RHS and produce a widen result.
16400   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16401   // => <2 x i64> <ae|cg>
16402   //
16403   // In other word, to have all the results, we need to perform two PMULxD:
16404   // 1. one with the even values.
16405   // 2. one with the odd values.
16406   // To achieve #2, with need to place the odd values at an even position.
16407   //
16408   // Place the odd value at an even position (basically, shift all values 1
16409   // step to the left):
16410   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16411   // <a|b|c|d> => <b|undef|d|undef>
16412   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16413   // <e|f|g|h> => <f|undef|h|undef>
16414   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16415
16416   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16417   // ints.
16418   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16419   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16420   unsigned Opcode =
16421       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16422   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16423   // => <2 x i64> <ae|cg>
16424   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16425                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16426   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16427   // => <2 x i64> <bf|dh>
16428   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16429                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16430
16431   // Shuffle it back into the right order.
16432   SDValue Highs, Lows;
16433   if (VT == MVT::v8i32) {
16434     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16435     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16436     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16437     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16438   } else {
16439     const int HighMask[] = {1, 5, 3, 7};
16440     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16441     const int LowMask[] = {0, 4, 2, 6};
16442     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16443   }
16444
16445   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16446   // unsigned multiply.
16447   if (IsSigned && !Subtarget->hasSSE41()) {
16448     SDValue ShAmt =
16449         DAG.getConstant(31, dl,
16450                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16451     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16452                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16453     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16454                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16455
16456     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16457     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16458   }
16459
16460   // The first result of MUL_LOHI is actually the low value, followed by the
16461   // high value.
16462   SDValue Ops[] = {Lows, Highs};
16463   return DAG.getMergeValues(Ops, dl);
16464 }
16465
16466 // Return true if the requred (according to Opcode) shift-imm form is natively
16467 // supported by the Subtarget
16468 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget, 
16469                                         unsigned Opcode) {
16470   if (VT.getScalarSizeInBits() < 16)
16471     return false;
16472  
16473   if (VT.is512BitVector() &&
16474       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16475     return true;
16476
16477   bool LShift = VT.is128BitVector() || 
16478     (VT.is256BitVector() && Subtarget->hasInt256());
16479
16480   bool AShift = LShift && (Subtarget->hasVLX() ||
16481     (VT != MVT::v2i64 && VT != MVT::v4i64));
16482   return (Opcode == ISD::SRA) ? AShift : LShift;
16483 }
16484
16485 // The shift amount is a variable, but it is the same for all vector lanes.
16486 // These instrcutions are defined together with shift-immediate.
16487 static 
16488 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget, 
16489                                       unsigned Opcode) {
16490   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16491 }
16492
16493 // Return true if the requred (according to Opcode) variable-shift form is
16494 // natively supported by the Subtarget
16495 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget, 
16496                                     unsigned Opcode) {
16497
16498   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16499     return false;
16500
16501   // vXi16 supported only on AVX-512, BWI
16502   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16503     return false;
16504
16505   if (VT.is512BitVector() || Subtarget->hasVLX())
16506     return true;
16507
16508   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16509   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16510   return (Opcode == ISD::SRA) ? AShift : LShift;
16511 }
16512
16513 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16514                                          const X86Subtarget *Subtarget) {
16515   MVT VT = Op.getSimpleValueType();
16516   SDLoc dl(Op);
16517   SDValue R = Op.getOperand(0);
16518   SDValue Amt = Op.getOperand(1);
16519
16520   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16521     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16522
16523   // Optimize shl/srl/sra with constant shift amount.
16524   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16525     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16526       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16527
16528       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16529         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16530
16531       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16532         unsigned NumElts = VT.getVectorNumElements();
16533         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16534
16535         if (Op.getOpcode() == ISD::SHL) {
16536           // Make a large shift.
16537           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16538                                                    R, ShiftAmt, DAG);
16539           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16540           // Zero out the rightmost bits.
16541           SmallVector<SDValue, 32> V(
16542               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16543           return DAG.getNode(ISD::AND, dl, VT, SHL,
16544                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16545         }
16546         if (Op.getOpcode() == ISD::SRL) {
16547           // Make a large shift.
16548           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16549                                                    R, ShiftAmt, DAG);
16550           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16551           // Zero out the leftmost bits.
16552           SmallVector<SDValue, 32> V(
16553               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16554           return DAG.getNode(ISD::AND, dl, VT, SRL,
16555                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16556         }
16557         if (Op.getOpcode() == ISD::SRA) {
16558           if (ShiftAmt == 7) {
16559             // R s>> 7  ===  R s< 0
16560             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16561             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16562           }
16563
16564           // R s>> a === ((R u>> a) ^ m) - m
16565           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16566           SmallVector<SDValue, 32> V(NumElts,
16567                                      DAG.getConstant(128 >> ShiftAmt, dl,
16568                                                      MVT::i8));
16569           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16570           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16571           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16572           return Res;
16573         }
16574         llvm_unreachable("Unknown shift opcode.");
16575       }
16576     }
16577   }
16578
16579   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16580   if (!Subtarget->is64Bit() &&
16581       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16582       Amt.getOpcode() == ISD::BITCAST &&
16583       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16584     Amt = Amt.getOperand(0);
16585     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16586                      VT.getVectorNumElements();
16587     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16588     uint64_t ShiftAmt = 0;
16589     for (unsigned i = 0; i != Ratio; ++i) {
16590       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16591       if (!C)
16592         return SDValue();
16593       // 6 == Log2(64)
16594       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16595     }
16596     // Check remaining shift amounts.
16597     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16598       uint64_t ShAmt = 0;
16599       for (unsigned j = 0; j != Ratio; ++j) {
16600         ConstantSDNode *C =
16601           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16602         if (!C)
16603           return SDValue();
16604         // 6 == Log2(64)
16605         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16606       }
16607       if (ShAmt != ShiftAmt)
16608         return SDValue();
16609     }
16610     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16611   }
16612
16613   return SDValue();
16614 }
16615
16616 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16617                                         const X86Subtarget* Subtarget) {
16618   MVT VT = Op.getSimpleValueType();
16619   SDLoc dl(Op);
16620   SDValue R = Op.getOperand(0);
16621   SDValue Amt = Op.getOperand(1);
16622
16623   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16624     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16625
16626   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16627     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16628
16629   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16630     SDValue BaseShAmt;
16631     EVT EltVT = VT.getVectorElementType();
16632
16633     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16634       // Check if this build_vector node is doing a splat.
16635       // If so, then set BaseShAmt equal to the splat value.
16636       BaseShAmt = BV->getSplatValue();
16637       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16638         BaseShAmt = SDValue();
16639     } else {
16640       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16641         Amt = Amt.getOperand(0);
16642
16643       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16644       if (SVN && SVN->isSplat()) {
16645         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16646         SDValue InVec = Amt.getOperand(0);
16647         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16648           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16649                  "Unexpected shuffle index found!");
16650           BaseShAmt = InVec.getOperand(SplatIdx);
16651         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16652            if (ConstantSDNode *C =
16653                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16654              if (C->getZExtValue() == SplatIdx)
16655                BaseShAmt = InVec.getOperand(1);
16656            }
16657         }
16658
16659         if (!BaseShAmt)
16660           // Avoid introducing an extract element from a shuffle.
16661           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16662                                   DAG.getIntPtrConstant(SplatIdx, dl));
16663       }
16664     }
16665
16666     if (BaseShAmt.getNode()) {
16667       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16668       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16669         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16670       else if (EltVT.bitsLT(MVT::i32))
16671         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16672
16673       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16674     }
16675   }
16676
16677   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16678   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16679       Amt.getOpcode() == ISD::BITCAST &&
16680       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16681     Amt = Amt.getOperand(0);
16682     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16683                      VT.getVectorNumElements();
16684     std::vector<SDValue> Vals(Ratio);
16685     for (unsigned i = 0; i != Ratio; ++i)
16686       Vals[i] = Amt.getOperand(i);
16687     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16688       for (unsigned j = 0; j != Ratio; ++j)
16689         if (Vals[j] != Amt.getOperand(i + j))
16690           return SDValue();
16691     }
16692     return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16693   }
16694   return SDValue();
16695 }
16696
16697 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16698                           SelectionDAG &DAG) {
16699   MVT VT = Op.getSimpleValueType();
16700   SDLoc dl(Op);
16701   SDValue R = Op.getOperand(0);
16702   SDValue Amt = Op.getOperand(1);
16703
16704   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16705   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16706
16707   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16708     return V;
16709
16710   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16711       return V;
16712
16713   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16714     return Op;
16715
16716   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16717   // shifts per-lane and then shuffle the partial results back together.
16718   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16719     // Splat the shift amounts so the scalar shifts above will catch it.
16720     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16721     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16722     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16723     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16724     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16725   }
16726
16727   // If possible, lower this packed shift into a vector multiply instead of
16728   // expanding it into a sequence of scalar shifts.
16729   // Do this only if the vector shift count is a constant build_vector.
16730   if (Op.getOpcode() == ISD::SHL &&
16731       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16732        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16733       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16734     SmallVector<SDValue, 8> Elts;
16735     EVT SVT = VT.getScalarType();
16736     unsigned SVTBits = SVT.getSizeInBits();
16737     const APInt &One = APInt(SVTBits, 1);
16738     unsigned NumElems = VT.getVectorNumElements();
16739
16740     for (unsigned i=0; i !=NumElems; ++i) {
16741       SDValue Op = Amt->getOperand(i);
16742       if (Op->getOpcode() == ISD::UNDEF) {
16743         Elts.push_back(Op);
16744         continue;
16745       }
16746
16747       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16748       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16749       uint64_t ShAmt = C.getZExtValue();
16750       if (ShAmt >= SVTBits) {
16751         Elts.push_back(DAG.getUNDEF(SVT));
16752         continue;
16753       }
16754       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16755     }
16756     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16757     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16758   }
16759
16760   // Lower SHL with variable shift amount.
16761   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16762     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16763
16764     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16765                      DAG.getConstant(0x3f800000U, dl, VT));
16766     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16767     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16768     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16769   }
16770
16771   // If possible, lower this shift as a sequence of two shifts by
16772   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16773   // Example:
16774   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16775   //
16776   // Could be rewritten as:
16777   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16778   //
16779   // The advantage is that the two shifts from the example would be
16780   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16781   // the vector shift into four scalar shifts plus four pairs of vector
16782   // insert/extract.
16783   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16784       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16785     unsigned TargetOpcode = X86ISD::MOVSS;
16786     bool CanBeSimplified;
16787     // The splat value for the first packed shift (the 'X' from the example).
16788     SDValue Amt1 = Amt->getOperand(0);
16789     // The splat value for the second packed shift (the 'Y' from the example).
16790     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16791                                         Amt->getOperand(2);
16792
16793     // See if it is possible to replace this node with a sequence of
16794     // two shifts followed by a MOVSS/MOVSD
16795     if (VT == MVT::v4i32) {
16796       // Check if it is legal to use a MOVSS.
16797       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16798                         Amt2 == Amt->getOperand(3);
16799       if (!CanBeSimplified) {
16800         // Otherwise, check if we can still simplify this node using a MOVSD.
16801         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16802                           Amt->getOperand(2) == Amt->getOperand(3);
16803         TargetOpcode = X86ISD::MOVSD;
16804         Amt2 = Amt->getOperand(2);
16805       }
16806     } else {
16807       // Do similar checks for the case where the machine value type
16808       // is MVT::v8i16.
16809       CanBeSimplified = Amt1 == Amt->getOperand(1);
16810       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16811         CanBeSimplified = Amt2 == Amt->getOperand(i);
16812
16813       if (!CanBeSimplified) {
16814         TargetOpcode = X86ISD::MOVSD;
16815         CanBeSimplified = true;
16816         Amt2 = Amt->getOperand(4);
16817         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16818           CanBeSimplified = Amt1 == Amt->getOperand(i);
16819         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16820           CanBeSimplified = Amt2 == Amt->getOperand(j);
16821       }
16822     }
16823
16824     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16825         isa<ConstantSDNode>(Amt2)) {
16826       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16827       EVT CastVT = MVT::v4i32;
16828       SDValue Splat1 =
16829         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16830       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16831       SDValue Splat2 =
16832         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16833       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16834       if (TargetOpcode == X86ISD::MOVSD)
16835         CastVT = MVT::v2i64;
16836       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16837       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16838       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16839                                             BitCast1, DAG);
16840       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16841     }
16842   }
16843
16844   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16845     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16846     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16847
16848     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16849     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16850     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16851
16852     // r = VSELECT(r, shl(r, 4), a);
16853     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16854     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16855
16856     // a += a
16857     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16858     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16859     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16860
16861     // r = VSELECT(r, shl(r, 2), a);
16862     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16863     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16864
16865     // a += a
16866     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16867     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16868     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16869
16870     // return VSELECT(r, r+r, a);
16871     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16872                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16873     return R;
16874   }
16875
16876   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16877   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16878   // solution better.
16879   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16880     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16881     unsigned ExtOpc =
16882         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16883     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16884     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16885     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16886                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16887   }
16888
16889   // Decompose 256-bit shifts into smaller 128-bit shifts.
16890   if (VT.is256BitVector()) {
16891     unsigned NumElems = VT.getVectorNumElements();
16892     MVT EltVT = VT.getVectorElementType();
16893     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16894
16895     // Extract the two vectors
16896     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16897     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16898
16899     // Recreate the shift amount vectors
16900     SDValue Amt1, Amt2;
16901     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16902       // Constant shift amount
16903       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16904       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16905       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16906
16907       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16908       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16909     } else {
16910       // Variable shift amount
16911       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16912       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16913     }
16914
16915     // Issue new vector shifts for the smaller types
16916     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16917     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16918
16919     // Concatenate the result back
16920     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16921   }
16922
16923   return SDValue();
16924 }
16925
16926 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16927   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16928   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16929   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16930   // has only one use.
16931   SDNode *N = Op.getNode();
16932   SDValue LHS = N->getOperand(0);
16933   SDValue RHS = N->getOperand(1);
16934   unsigned BaseOp = 0;
16935   unsigned Cond = 0;
16936   SDLoc DL(Op);
16937   switch (Op.getOpcode()) {
16938   default: llvm_unreachable("Unknown ovf instruction!");
16939   case ISD::SADDO:
16940     // A subtract of one will be selected as a INC. Note that INC doesn't
16941     // set CF, so we can't do this for UADDO.
16942     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16943       if (C->isOne()) {
16944         BaseOp = X86ISD::INC;
16945         Cond = X86::COND_O;
16946         break;
16947       }
16948     BaseOp = X86ISD::ADD;
16949     Cond = X86::COND_O;
16950     break;
16951   case ISD::UADDO:
16952     BaseOp = X86ISD::ADD;
16953     Cond = X86::COND_B;
16954     break;
16955   case ISD::SSUBO:
16956     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16957     // set CF, so we can't do this for USUBO.
16958     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16959       if (C->isOne()) {
16960         BaseOp = X86ISD::DEC;
16961         Cond = X86::COND_O;
16962         break;
16963       }
16964     BaseOp = X86ISD::SUB;
16965     Cond = X86::COND_O;
16966     break;
16967   case ISD::USUBO:
16968     BaseOp = X86ISD::SUB;
16969     Cond = X86::COND_B;
16970     break;
16971   case ISD::SMULO:
16972     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16973     Cond = X86::COND_O;
16974     break;
16975   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16976     if (N->getValueType(0) == MVT::i8) {
16977       BaseOp = X86ISD::UMUL8;
16978       Cond = X86::COND_O;
16979       break;
16980     }
16981     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16982                                  MVT::i32);
16983     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16984
16985     SDValue SetCC =
16986       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16987                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
16988                   SDValue(Sum.getNode(), 2));
16989
16990     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16991   }
16992   }
16993
16994   // Also sets EFLAGS.
16995   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16996   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16997
16998   SDValue SetCC =
16999     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17000                 DAG.getConstant(Cond, DL, MVT::i32),
17001                 SDValue(Sum.getNode(), 1));
17002
17003   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17004 }
17005
17006 /// Returns true if the operand type is exactly twice the native width, and
17007 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17008 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17009 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17010 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17011   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17012
17013   if (OpWidth == 64)
17014     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17015   else if (OpWidth == 128)
17016     return Subtarget->hasCmpxchg16b();
17017   else
17018     return false;
17019 }
17020
17021 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17022   return needsCmpXchgNb(SI->getValueOperand()->getType());
17023 }
17024
17025 // Note: this turns large loads into lock cmpxchg8b/16b.
17026 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17027 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17028   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17029   return needsCmpXchgNb(PTy->getElementType());
17030 }
17031
17032 TargetLoweringBase::AtomicRMWExpansionKind
17033 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17034   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17035   const Type *MemType = AI->getType();
17036
17037   // If the operand is too big, we must see if cmpxchg8/16b is available
17038   // and default to library calls otherwise.
17039   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17040     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17041                                    : AtomicRMWExpansionKind::None;
17042   }
17043
17044   AtomicRMWInst::BinOp Op = AI->getOperation();
17045   switch (Op) {
17046   default:
17047     llvm_unreachable("Unknown atomic operation");
17048   case AtomicRMWInst::Xchg:
17049   case AtomicRMWInst::Add:
17050   case AtomicRMWInst::Sub:
17051     // It's better to use xadd, xsub or xchg for these in all cases.
17052     return AtomicRMWExpansionKind::None;
17053   case AtomicRMWInst::Or:
17054   case AtomicRMWInst::And:
17055   case AtomicRMWInst::Xor:
17056     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17057     // prefix to a normal instruction for these operations.
17058     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17059                             : AtomicRMWExpansionKind::None;
17060   case AtomicRMWInst::Nand:
17061   case AtomicRMWInst::Max:
17062   case AtomicRMWInst::Min:
17063   case AtomicRMWInst::UMax:
17064   case AtomicRMWInst::UMin:
17065     // These always require a non-trivial set of data operations on x86. We must
17066     // use a cmpxchg loop.
17067     return AtomicRMWExpansionKind::CmpXChg;
17068   }
17069 }
17070
17071 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17072   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17073   // no-sse2). There isn't any reason to disable it if the target processor
17074   // supports it.
17075   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17076 }
17077
17078 LoadInst *
17079 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17080   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17081   const Type *MemType = AI->getType();
17082   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17083   // there is no benefit in turning such RMWs into loads, and it is actually
17084   // harmful as it introduces a mfence.
17085   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17086     return nullptr;
17087
17088   auto Builder = IRBuilder<>(AI);
17089   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17090   auto SynchScope = AI->getSynchScope();
17091   // We must restrict the ordering to avoid generating loads with Release or
17092   // ReleaseAcquire orderings.
17093   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17094   auto Ptr = AI->getPointerOperand();
17095
17096   // Before the load we need a fence. Here is an example lifted from
17097   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17098   // is required:
17099   // Thread 0:
17100   //   x.store(1, relaxed);
17101   //   r1 = y.fetch_add(0, release);
17102   // Thread 1:
17103   //   y.fetch_add(42, acquire);
17104   //   r2 = x.load(relaxed);
17105   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17106   // lowered to just a load without a fence. A mfence flushes the store buffer,
17107   // making the optimization clearly correct.
17108   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17109   // otherwise, we might be able to be more agressive on relaxed idempotent
17110   // rmw. In practice, they do not look useful, so we don't try to be
17111   // especially clever.
17112   if (SynchScope == SingleThread)
17113     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17114     // the IR level, so we must wrap it in an intrinsic.
17115     return nullptr;
17116
17117   if (!hasMFENCE(*Subtarget))
17118     // FIXME: it might make sense to use a locked operation here but on a
17119     // different cache-line to prevent cache-line bouncing. In practice it
17120     // is probably a small win, and x86 processors without mfence are rare
17121     // enough that we do not bother.
17122     return nullptr;
17123
17124   Function *MFence =
17125       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17126   Builder.CreateCall(MFence, {});
17127
17128   // Finally we can emit the atomic load.
17129   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17130           AI->getType()->getPrimitiveSizeInBits());
17131   Loaded->setAtomic(Order, SynchScope);
17132   AI->replaceAllUsesWith(Loaded);
17133   AI->eraseFromParent();
17134   return Loaded;
17135 }
17136
17137 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17138                                  SelectionDAG &DAG) {
17139   SDLoc dl(Op);
17140   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17141     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17142   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17143     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17144
17145   // The only fence that needs an instruction is a sequentially-consistent
17146   // cross-thread fence.
17147   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17148     if (hasMFENCE(*Subtarget))
17149       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17150
17151     SDValue Chain = Op.getOperand(0);
17152     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17153     SDValue Ops[] = {
17154       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17155       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17156       DAG.getRegister(0, MVT::i32),            // Index
17157       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17158       DAG.getRegister(0, MVT::i32),            // Segment.
17159       Zero,
17160       Chain
17161     };
17162     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17163     return SDValue(Res, 0);
17164   }
17165
17166   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17167   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17168 }
17169
17170 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17171                              SelectionDAG &DAG) {
17172   MVT T = Op.getSimpleValueType();
17173   SDLoc DL(Op);
17174   unsigned Reg = 0;
17175   unsigned size = 0;
17176   switch(T.SimpleTy) {
17177   default: llvm_unreachable("Invalid value type!");
17178   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17179   case MVT::i16: Reg = X86::AX;  size = 2; break;
17180   case MVT::i32: Reg = X86::EAX; size = 4; break;
17181   case MVT::i64:
17182     assert(Subtarget->is64Bit() && "Node not type legal!");
17183     Reg = X86::RAX; size = 8;
17184     break;
17185   }
17186   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17187                                   Op.getOperand(2), SDValue());
17188   SDValue Ops[] = { cpIn.getValue(0),
17189                     Op.getOperand(1),
17190                     Op.getOperand(3),
17191                     DAG.getTargetConstant(size, DL, MVT::i8),
17192                     cpIn.getValue(1) };
17193   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17194   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17195   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17196                                            Ops, T, MMO);
17197
17198   SDValue cpOut =
17199     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17200   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17201                                       MVT::i32, cpOut.getValue(2));
17202   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17203                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17204                                 EFLAGS);
17205
17206   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17207   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17208   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17209   return SDValue();
17210 }
17211
17212 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17213                             SelectionDAG &DAG) {
17214   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17215   MVT DstVT = Op.getSimpleValueType();
17216
17217   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17218     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17219     if (DstVT != MVT::f64)
17220       // This conversion needs to be expanded.
17221       return SDValue();
17222
17223     SDValue InVec = Op->getOperand(0);
17224     SDLoc dl(Op);
17225     unsigned NumElts = SrcVT.getVectorNumElements();
17226     EVT SVT = SrcVT.getVectorElementType();
17227
17228     // Widen the vector in input in the case of MVT::v2i32.
17229     // Example: from MVT::v2i32 to MVT::v4i32.
17230     SmallVector<SDValue, 16> Elts;
17231     for (unsigned i = 0, e = NumElts; i != e; ++i)
17232       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17233                                  DAG.getIntPtrConstant(i, dl)));
17234
17235     // Explicitly mark the extra elements as Undef.
17236     Elts.append(NumElts, DAG.getUNDEF(SVT));
17237
17238     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17239     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17240     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17241     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17242                        DAG.getIntPtrConstant(0, dl));
17243   }
17244
17245   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17246          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17247   assert((DstVT == MVT::i64 ||
17248           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17249          "Unexpected custom BITCAST");
17250   // i64 <=> MMX conversions are Legal.
17251   if (SrcVT==MVT::i64 && DstVT.isVector())
17252     return Op;
17253   if (DstVT==MVT::i64 && SrcVT.isVector())
17254     return Op;
17255   // MMX <=> MMX conversions are Legal.
17256   if (SrcVT.isVector() && DstVT.isVector())
17257     return Op;
17258   // All other conversions need to be expanded.
17259   return SDValue();
17260 }
17261
17262 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17263                           SelectionDAG &DAG) {
17264   SDNode *Node = Op.getNode();
17265   SDLoc dl(Node);
17266
17267   Op = Op.getOperand(0);
17268   EVT VT = Op.getValueType();
17269   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17270          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17271
17272   unsigned NumElts = VT.getVectorNumElements();
17273   EVT EltVT = VT.getVectorElementType();
17274   unsigned Len = EltVT.getSizeInBits();
17275
17276   // This is the vectorized version of the "best" algorithm from
17277   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17278   // with a minor tweak to use a series of adds + shifts instead of vector
17279   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17280   //
17281   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17282   //  v8i32 => Always profitable
17283   //
17284   // FIXME: There a couple of possible improvements:
17285   //
17286   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17287   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17288   //
17289   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17290          "CTPOP not implemented for this vector element type.");
17291
17292   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17293   // extra legalization.
17294   bool NeedsBitcast = EltVT == MVT::i32;
17295   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17296
17297   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17298                                   EltVT);
17299   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17300                                   EltVT);
17301   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17302                                   EltVT);
17303
17304   // v = v - ((v >> 1) & 0x55555555...)
17305   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17306   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17307   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17308   if (NeedsBitcast)
17309     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17310
17311   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17312   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17313   if (NeedsBitcast)
17314     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17315
17316   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17317   if (VT != And.getValueType())
17318     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17319   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17320
17321   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17322   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17323   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17324   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17325   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17326
17327   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17328   if (NeedsBitcast) {
17329     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17330     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17331     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17332   }
17333
17334   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17335   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17336   if (VT != AndRHS.getValueType()) {
17337     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17338     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17339   }
17340   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17341
17342   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17343   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17344   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17345   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17346   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17347
17348   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17349   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17350   if (NeedsBitcast) {
17351     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17352     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17353   }
17354   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17355   if (VT != And.getValueType())
17356     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17357
17358   // The algorithm mentioned above uses:
17359   //    v = (v * 0x01010101...) >> (Len - 8)
17360   //
17361   // Change it to use vector adds + vector shifts which yield faster results on
17362   // Haswell than using vector integer multiplication.
17363   //
17364   // For i32 elements:
17365   //    v = v + (v >> 8)
17366   //    v = v + (v >> 16)
17367   //
17368   // For i64 elements:
17369   //    v = v + (v >> 8)
17370   //    v = v + (v >> 16)
17371   //    v = v + (v >> 32)
17372   //
17373   Add = And;
17374   SmallVector<SDValue, 8> Csts;
17375   for (unsigned i = 8; i <= Len/2; i *= 2) {
17376     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17377     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17378     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17379     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17380     Csts.clear();
17381   }
17382
17383   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17384   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17385                                   EltVT);
17386   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17387   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17388   if (NeedsBitcast) {
17389     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17390     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17391   }
17392   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17393   if (VT != And.getValueType())
17394     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17395
17396   return And;
17397 }
17398
17399 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17400   SDNode *Node = Op.getNode();
17401   SDLoc dl(Node);
17402   EVT T = Node->getValueType(0);
17403   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17404                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17405   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17406                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17407                        Node->getOperand(0),
17408                        Node->getOperand(1), negOp,
17409                        cast<AtomicSDNode>(Node)->getMemOperand(),
17410                        cast<AtomicSDNode>(Node)->getOrdering(),
17411                        cast<AtomicSDNode>(Node)->getSynchScope());
17412 }
17413
17414 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17415   SDNode *Node = Op.getNode();
17416   SDLoc dl(Node);
17417   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17418
17419   // Convert seq_cst store -> xchg
17420   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17421   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17422   //        (The only way to get a 16-byte store is cmpxchg16b)
17423   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17424   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17425       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17426     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17427                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17428                                  Node->getOperand(0),
17429                                  Node->getOperand(1), Node->getOperand(2),
17430                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17431                                  cast<AtomicSDNode>(Node)->getOrdering(),
17432                                  cast<AtomicSDNode>(Node)->getSynchScope());
17433     return Swap.getValue(1);
17434   }
17435   // Other atomic stores have a simple pattern.
17436   return Op;
17437 }
17438
17439 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17440   EVT VT = Op.getNode()->getSimpleValueType(0);
17441
17442   // Let legalize expand this if it isn't a legal type yet.
17443   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17444     return SDValue();
17445
17446   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17447
17448   unsigned Opc;
17449   bool ExtraOp = false;
17450   switch (Op.getOpcode()) {
17451   default: llvm_unreachable("Invalid code");
17452   case ISD::ADDC: Opc = X86ISD::ADD; break;
17453   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17454   case ISD::SUBC: Opc = X86ISD::SUB; break;
17455   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17456   }
17457
17458   if (!ExtraOp)
17459     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17460                        Op.getOperand(1));
17461   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17462                      Op.getOperand(1), Op.getOperand(2));
17463 }
17464
17465 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17466                             SelectionDAG &DAG) {
17467   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17468
17469   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17470   // which returns the values as { float, float } (in XMM0) or
17471   // { double, double } (which is returned in XMM0, XMM1).
17472   SDLoc dl(Op);
17473   SDValue Arg = Op.getOperand(0);
17474   EVT ArgVT = Arg.getValueType();
17475   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17476
17477   TargetLowering::ArgListTy Args;
17478   TargetLowering::ArgListEntry Entry;
17479
17480   Entry.Node = Arg;
17481   Entry.Ty = ArgTy;
17482   Entry.isSExt = false;
17483   Entry.isZExt = false;
17484   Args.push_back(Entry);
17485
17486   bool isF64 = ArgVT == MVT::f64;
17487   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17488   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17489   // the results are returned via SRet in memory.
17490   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17491   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17492   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17493
17494   Type *RetTy = isF64
17495     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17496     : (Type*)VectorType::get(ArgTy, 4);
17497
17498   TargetLowering::CallLoweringInfo CLI(DAG);
17499   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17500     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17501
17502   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17503
17504   if (isF64)
17505     // Returned in xmm0 and xmm1.
17506     return CallResult.first;
17507
17508   // Returned in bits 0:31 and 32:64 xmm0.
17509   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17510                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17511   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17512                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17513   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17514   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17515 }
17516
17517 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17518                              SelectionDAG &DAG) {
17519   assert(Subtarget->hasAVX512() &&
17520          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17521
17522   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17523   EVT VT = N->getValue().getValueType();
17524   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17525   SDLoc dl(Op);
17526
17527   // X86 scatter kills mask register, so its type should be added to
17528   // the list of return values
17529   if (N->getNumValues() == 1) {
17530     SDValue Index = N->getIndex();
17531     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17532         !Index.getValueType().is512BitVector())
17533       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17534
17535     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17536     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17537                       N->getOperand(3), Index };
17538
17539     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17540     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17541     return SDValue(NewScatter.getNode(), 0);
17542   }
17543   return Op;
17544 }
17545
17546 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17547                             SelectionDAG &DAG) {
17548   assert(Subtarget->hasAVX512() &&
17549          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17550
17551   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17552   EVT VT = Op.getValueType();
17553   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17554   SDLoc dl(Op);
17555
17556   SDValue Index = N->getIndex();
17557   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17558       !Index.getValueType().is512BitVector()) {
17559     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17560     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17561                       N->getOperand(3), Index };
17562     DAG.UpdateNodeOperands(N, Ops);
17563   }
17564   return Op;
17565 }
17566
17567 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17568                                                     SelectionDAG &DAG) const {
17569   // TODO: Eventually, the lowering of these nodes should be informed by or
17570   // deferred to the GC strategy for the function in which they appear. For
17571   // now, however, they must be lowered to something. Since they are logically
17572   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17573   // require special handling for these nodes), lower them as literal NOOPs for
17574   // the time being.
17575   SmallVector<SDValue, 2> Ops;
17576
17577   Ops.push_back(Op.getOperand(0));
17578   if (Op->getGluedNode())
17579     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17580
17581   SDLoc OpDL(Op);
17582   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17583   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17584
17585   return NOOP;
17586 }
17587
17588 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17589                                                   SelectionDAG &DAG) const {
17590   // TODO: Eventually, the lowering of these nodes should be informed by or
17591   // deferred to the GC strategy for the function in which they appear. For
17592   // now, however, they must be lowered to something. Since they are logically
17593   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17594   // require special handling for these nodes), lower them as literal NOOPs for
17595   // the time being.
17596   SmallVector<SDValue, 2> Ops;
17597
17598   Ops.push_back(Op.getOperand(0));
17599   if (Op->getGluedNode())
17600     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17601
17602   SDLoc OpDL(Op);
17603   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17604   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17605
17606   return NOOP;
17607 }
17608
17609 /// LowerOperation - Provide custom lowering hooks for some operations.
17610 ///
17611 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17612   switch (Op.getOpcode()) {
17613   default: llvm_unreachable("Should not custom lower this!");
17614   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17615   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17616     return LowerCMP_SWAP(Op, Subtarget, DAG);
17617   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17618   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17619   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17620   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17621   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17622   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17623   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17624   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17625   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17626   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17627   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17628   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17629   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17630   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17631   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17632   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17633   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17634   case ISD::SHL_PARTS:
17635   case ISD::SRA_PARTS:
17636   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17637   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17638   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17639   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17640   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17641   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17642   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17643   case ISD::SIGN_EXTEND_VECTOR_INREG:
17644     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
17645   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17646   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17647   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17648   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17649   case ISD::FABS:
17650   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17651   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17652   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17653   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17654   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17655   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17656   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17657   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17658   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17659   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17660   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17661   case ISD::INTRINSIC_VOID:
17662   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17663   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17664   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17665   case ISD::FRAME_TO_ARGS_OFFSET:
17666                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17667   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17668   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17669   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17670   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17671   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17672   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17673   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17674   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17675   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17676   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17677   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17678   case ISD::UMUL_LOHI:
17679   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17680   case ISD::SRA:
17681   case ISD::SRL:
17682   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17683   case ISD::SADDO:
17684   case ISD::UADDO:
17685   case ISD::SSUBO:
17686   case ISD::USUBO:
17687   case ISD::SMULO:
17688   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17689   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17690   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17691   case ISD::ADDC:
17692   case ISD::ADDE:
17693   case ISD::SUBC:
17694   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17695   case ISD::ADD:                return LowerADD(Op, DAG);
17696   case ISD::SUB:                return LowerSUB(Op, DAG);
17697   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17698   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17699   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17700   case ISD::GC_TRANSITION_START:
17701                                 return LowerGC_TRANSITION_START(Op, DAG);
17702   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17703   }
17704 }
17705
17706 /// ReplaceNodeResults - Replace a node with an illegal result type
17707 /// with a new node built out of custom code.
17708 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17709                                            SmallVectorImpl<SDValue>&Results,
17710                                            SelectionDAG &DAG) const {
17711   SDLoc dl(N);
17712   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17713   switch (N->getOpcode()) {
17714   default:
17715     llvm_unreachable("Do not know how to custom type legalize this operation!");
17716   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17717   case X86ISD::FMINC:
17718   case X86ISD::FMIN:
17719   case X86ISD::FMAXC:
17720   case X86ISD::FMAX: {
17721     EVT VT = N->getValueType(0);
17722     if (VT != MVT::v2f32)
17723       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17724     SDValue UNDEF = DAG.getUNDEF(VT);
17725     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17726                               N->getOperand(0), UNDEF);
17727     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17728                               N->getOperand(1), UNDEF);
17729     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17730     return;
17731   }
17732   case ISD::SIGN_EXTEND_INREG:
17733   case ISD::ADDC:
17734   case ISD::ADDE:
17735   case ISD::SUBC:
17736   case ISD::SUBE:
17737     // We don't want to expand or promote these.
17738     return;
17739   case ISD::SDIV:
17740   case ISD::UDIV:
17741   case ISD::SREM:
17742   case ISD::UREM:
17743   case ISD::SDIVREM:
17744   case ISD::UDIVREM: {
17745     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17746     Results.push_back(V);
17747     return;
17748   }
17749   case ISD::FP_TO_SINT:
17750     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
17751     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17752     if (N->getOperand(0).getValueType() == MVT::f16)
17753       break;
17754     // fallthrough
17755   case ISD::FP_TO_UINT: {
17756     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17757
17758     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17759       return;
17760
17761     std::pair<SDValue,SDValue> Vals =
17762         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17763     SDValue FIST = Vals.first, StackSlot = Vals.second;
17764     if (FIST.getNode()) {
17765       EVT VT = N->getValueType(0);
17766       // Return a load from the stack slot.
17767       if (StackSlot.getNode())
17768         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17769                                       MachinePointerInfo(),
17770                                       false, false, false, 0));
17771       else
17772         Results.push_back(FIST);
17773     }
17774     return;
17775   }
17776   case ISD::UINT_TO_FP: {
17777     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17778     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17779         N->getValueType(0) != MVT::v2f32)
17780       return;
17781     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17782                                  N->getOperand(0));
17783     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17784                                      MVT::f64);
17785     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17786     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17787                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17788     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17789     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17790     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17791     return;
17792   }
17793   case ISD::FP_ROUND: {
17794     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17795         return;
17796     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17797     Results.push_back(V);
17798     return;
17799   }
17800   case ISD::FP_EXTEND: {
17801     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17802     // No other ValueType for FP_EXTEND should reach this point.
17803     assert(N->getValueType(0) == MVT::v2f32 &&
17804            "Do not know how to legalize this Node");
17805     return;
17806   }
17807   case ISD::INTRINSIC_W_CHAIN: {
17808     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17809     switch (IntNo) {
17810     default : llvm_unreachable("Do not know how to custom type "
17811                                "legalize this intrinsic operation!");
17812     case Intrinsic::x86_rdtsc:
17813       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17814                                      Results);
17815     case Intrinsic::x86_rdtscp:
17816       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17817                                      Results);
17818     case Intrinsic::x86_rdpmc:
17819       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17820     }
17821   }
17822   case ISD::READCYCLECOUNTER: {
17823     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17824                                    Results);
17825   }
17826   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17827     EVT T = N->getValueType(0);
17828     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17829     bool Regs64bit = T == MVT::i128;
17830     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17831     SDValue cpInL, cpInH;
17832     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17833                         DAG.getConstant(0, dl, HalfT));
17834     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17835                         DAG.getConstant(1, dl, HalfT));
17836     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17837                              Regs64bit ? X86::RAX : X86::EAX,
17838                              cpInL, SDValue());
17839     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17840                              Regs64bit ? X86::RDX : X86::EDX,
17841                              cpInH, cpInL.getValue(1));
17842     SDValue swapInL, swapInH;
17843     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17844                           DAG.getConstant(0, dl, HalfT));
17845     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17846                           DAG.getConstant(1, dl, HalfT));
17847     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17848                                Regs64bit ? X86::RBX : X86::EBX,
17849                                swapInL, cpInH.getValue(1));
17850     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17851                                Regs64bit ? X86::RCX : X86::ECX,
17852                                swapInH, swapInL.getValue(1));
17853     SDValue Ops[] = { swapInH.getValue(0),
17854                       N->getOperand(1),
17855                       swapInH.getValue(1) };
17856     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17857     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17858     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17859                                   X86ISD::LCMPXCHG8_DAG;
17860     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17861     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17862                                         Regs64bit ? X86::RAX : X86::EAX,
17863                                         HalfT, Result.getValue(1));
17864     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17865                                         Regs64bit ? X86::RDX : X86::EDX,
17866                                         HalfT, cpOutL.getValue(2));
17867     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17868
17869     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17870                                         MVT::i32, cpOutH.getValue(2));
17871     SDValue Success =
17872         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17873                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17874     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17875
17876     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17877     Results.push_back(Success);
17878     Results.push_back(EFLAGS.getValue(1));
17879     return;
17880   }
17881   case ISD::ATOMIC_SWAP:
17882   case ISD::ATOMIC_LOAD_ADD:
17883   case ISD::ATOMIC_LOAD_SUB:
17884   case ISD::ATOMIC_LOAD_AND:
17885   case ISD::ATOMIC_LOAD_OR:
17886   case ISD::ATOMIC_LOAD_XOR:
17887   case ISD::ATOMIC_LOAD_NAND:
17888   case ISD::ATOMIC_LOAD_MIN:
17889   case ISD::ATOMIC_LOAD_MAX:
17890   case ISD::ATOMIC_LOAD_UMIN:
17891   case ISD::ATOMIC_LOAD_UMAX:
17892   case ISD::ATOMIC_LOAD: {
17893     // Delegate to generic TypeLegalization. Situations we can really handle
17894     // should have already been dealt with by AtomicExpandPass.cpp.
17895     break;
17896   }
17897   case ISD::BITCAST: {
17898     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17899     EVT DstVT = N->getValueType(0);
17900     EVT SrcVT = N->getOperand(0)->getValueType(0);
17901
17902     if (SrcVT != MVT::f64 ||
17903         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17904       return;
17905
17906     unsigned NumElts = DstVT.getVectorNumElements();
17907     EVT SVT = DstVT.getVectorElementType();
17908     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17909     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17910                                    MVT::v2f64, N->getOperand(0));
17911     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17912
17913     if (ExperimentalVectorWideningLegalization) {
17914       // If we are legalizing vectors by widening, we already have the desired
17915       // legal vector type, just return it.
17916       Results.push_back(ToVecInt);
17917       return;
17918     }
17919
17920     SmallVector<SDValue, 8> Elts;
17921     for (unsigned i = 0, e = NumElts; i != e; ++i)
17922       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17923                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17924
17925     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17926   }
17927   }
17928 }
17929
17930 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17931   switch ((X86ISD::NodeType)Opcode) {
17932   case X86ISD::FIRST_NUMBER:       break;
17933   case X86ISD::BSF:                return "X86ISD::BSF";
17934   case X86ISD::BSR:                return "X86ISD::BSR";
17935   case X86ISD::SHLD:               return "X86ISD::SHLD";
17936   case X86ISD::SHRD:               return "X86ISD::SHRD";
17937   case X86ISD::FAND:               return "X86ISD::FAND";
17938   case X86ISD::FANDN:              return "X86ISD::FANDN";
17939   case X86ISD::FOR:                return "X86ISD::FOR";
17940   case X86ISD::FXOR:               return "X86ISD::FXOR";
17941   case X86ISD::FSRL:               return "X86ISD::FSRL";
17942   case X86ISD::FILD:               return "X86ISD::FILD";
17943   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17944   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17945   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17946   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17947   case X86ISD::FLD:                return "X86ISD::FLD";
17948   case X86ISD::FST:                return "X86ISD::FST";
17949   case X86ISD::CALL:               return "X86ISD::CALL";
17950   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17951   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17952   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17953   case X86ISD::BT:                 return "X86ISD::BT";
17954   case X86ISD::CMP:                return "X86ISD::CMP";
17955   case X86ISD::COMI:               return "X86ISD::COMI";
17956   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17957   case X86ISD::CMPM:               return "X86ISD::CMPM";
17958   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17959   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
17960   case X86ISD::SETCC:              return "X86ISD::SETCC";
17961   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17962   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17963   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
17964   case X86ISD::CMOV:               return "X86ISD::CMOV";
17965   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17966   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17967   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17968   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17969   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17970   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17971   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17972   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
17973   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
17974   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
17975   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17976   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17977   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17978   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17979   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17980   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
17981   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17982   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17983   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17984   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17985   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17986   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
17987   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17988   case X86ISD::HADD:               return "X86ISD::HADD";
17989   case X86ISD::HSUB:               return "X86ISD::HSUB";
17990   case X86ISD::FHADD:              return "X86ISD::FHADD";
17991   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17992   case X86ISD::UMAX:               return "X86ISD::UMAX";
17993   case X86ISD::UMIN:               return "X86ISD::UMIN";
17994   case X86ISD::SMAX:               return "X86ISD::SMAX";
17995   case X86ISD::SMIN:               return "X86ISD::SMIN";
17996   case X86ISD::FMAX:               return "X86ISD::FMAX";
17997   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
17998   case X86ISD::FMIN:               return "X86ISD::FMIN";
17999   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18000   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18001   case X86ISD::FMINC:              return "X86ISD::FMINC";
18002   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18003   case X86ISD::FRCP:               return "X86ISD::FRCP";
18004   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18005   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18006   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18007   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18008   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18009   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18010   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18011   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18012   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18013   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18014   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18015   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18016   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18017   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18018   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18019   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18020   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18021   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18022   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18023   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18024   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18025   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18026   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18027   case X86ISD::VSHL:               return "X86ISD::VSHL";
18028   case X86ISD::VSRL:               return "X86ISD::VSRL";
18029   case X86ISD::VSRA:               return "X86ISD::VSRA";
18030   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18031   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18032   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18033   case X86ISD::CMPP:               return "X86ISD::CMPP";
18034   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18035   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18036   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18037   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18038   case X86ISD::ADD:                return "X86ISD::ADD";
18039   case X86ISD::SUB:                return "X86ISD::SUB";
18040   case X86ISD::ADC:                return "X86ISD::ADC";
18041   case X86ISD::SBB:                return "X86ISD::SBB";
18042   case X86ISD::SMUL:               return "X86ISD::SMUL";
18043   case X86ISD::UMUL:               return "X86ISD::UMUL";
18044   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18045   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18046   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18047   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18048   case X86ISD::INC:                return "X86ISD::INC";
18049   case X86ISD::DEC:                return "X86ISD::DEC";
18050   case X86ISD::OR:                 return "X86ISD::OR";
18051   case X86ISD::XOR:                return "X86ISD::XOR";
18052   case X86ISD::AND:                return "X86ISD::AND";
18053   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18054   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18055   case X86ISD::PTEST:              return "X86ISD::PTEST";
18056   case X86ISD::TESTP:              return "X86ISD::TESTP";
18057   case X86ISD::TESTM:              return "X86ISD::TESTM";
18058   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18059   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18060   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18061   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18062   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18063   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18064   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18065   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18066   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18067   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18068   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18069   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18070   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18071   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18072   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18073   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18074   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18075   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18076   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18077   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18078   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18079   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18080   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18081   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18082   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18083   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18084   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18085   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18086   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18087   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18088   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18089   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18090   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18091   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18092   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18093   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18094   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18095   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18096   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18097   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18098   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18099   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18100   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18101   case X86ISD::SAHF:               return "X86ISD::SAHF";
18102   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18103   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18104   case X86ISD::FMADD:              return "X86ISD::FMADD";
18105   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18106   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18107   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18108   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18109   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18110   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18111   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18112   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18113   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18114   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18115   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18116   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18117   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18118   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18119   case X86ISD::XTEST:              return "X86ISD::XTEST";
18120   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18121   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18122   case X86ISD::SELECT:             return "X86ISD::SELECT";
18123   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18124   case X86ISD::RCP28:              return "X86ISD::RCP28";
18125   case X86ISD::EXP2:               return "X86ISD::EXP2";
18126   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18127   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18128   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18129   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18130   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18131   case X86ISD::ADDS:               return "X86ISD::ADDS";
18132   case X86ISD::SUBS:               return "X86ISD::SUBS";
18133   }
18134   return nullptr;
18135 }
18136
18137 // isLegalAddressingMode - Return true if the addressing mode represented
18138 // by AM is legal for this target, for a load/store of the specified type.
18139 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18140                                               Type *Ty) const {
18141   // X86 supports extremely general addressing modes.
18142   CodeModel::Model M = getTargetMachine().getCodeModel();
18143   Reloc::Model R = getTargetMachine().getRelocationModel();
18144
18145   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18146   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18147     return false;
18148
18149   if (AM.BaseGV) {
18150     unsigned GVFlags =
18151       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18152
18153     // If a reference to this global requires an extra load, we can't fold it.
18154     if (isGlobalStubReference(GVFlags))
18155       return false;
18156
18157     // If BaseGV requires a register for the PIC base, we cannot also have a
18158     // BaseReg specified.
18159     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18160       return false;
18161
18162     // If lower 4G is not available, then we must use rip-relative addressing.
18163     if ((M != CodeModel::Small || R != Reloc::Static) &&
18164         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18165       return false;
18166   }
18167
18168   switch (AM.Scale) {
18169   case 0:
18170   case 1:
18171   case 2:
18172   case 4:
18173   case 8:
18174     // These scales always work.
18175     break;
18176   case 3:
18177   case 5:
18178   case 9:
18179     // These scales are formed with basereg+scalereg.  Only accept if there is
18180     // no basereg yet.
18181     if (AM.HasBaseReg)
18182       return false;
18183     break;
18184   default:  // Other stuff never works.
18185     return false;
18186   }
18187
18188   return true;
18189 }
18190
18191 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18192   unsigned Bits = Ty->getScalarSizeInBits();
18193
18194   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18195   // particularly cheaper than those without.
18196   if (Bits == 8)
18197     return false;
18198
18199   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18200   // variable shifts just as cheap as scalar ones.
18201   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18202     return false;
18203
18204   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18205   // fully general vector.
18206   return true;
18207 }
18208
18209 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18210   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18211     return false;
18212   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18213   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18214   return NumBits1 > NumBits2;
18215 }
18216
18217 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18218   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18219     return false;
18220
18221   if (!isTypeLegal(EVT::getEVT(Ty1)))
18222     return false;
18223
18224   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18225
18226   // Assuming the caller doesn't have a zeroext or signext return parameter,
18227   // truncation all the way down to i1 is valid.
18228   return true;
18229 }
18230
18231 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18232   return isInt<32>(Imm);
18233 }
18234
18235 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18236   // Can also use sub to handle negated immediates.
18237   return isInt<32>(Imm);
18238 }
18239
18240 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18241   if (!VT1.isInteger() || !VT2.isInteger())
18242     return false;
18243   unsigned NumBits1 = VT1.getSizeInBits();
18244   unsigned NumBits2 = VT2.getSizeInBits();
18245   return NumBits1 > NumBits2;
18246 }
18247
18248 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18249   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18250   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18251 }
18252
18253 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18254   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18255   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18256 }
18257
18258 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18259   EVT VT1 = Val.getValueType();
18260   if (isZExtFree(VT1, VT2))
18261     return true;
18262
18263   if (Val.getOpcode() != ISD::LOAD)
18264     return false;
18265
18266   if (!VT1.isSimple() || !VT1.isInteger() ||
18267       !VT2.isSimple() || !VT2.isInteger())
18268     return false;
18269
18270   switch (VT1.getSimpleVT().SimpleTy) {
18271   default: break;
18272   case MVT::i8:
18273   case MVT::i16:
18274   case MVT::i32:
18275     // X86 has 8, 16, and 32-bit zero-extending loads.
18276     return true;
18277   }
18278
18279   return false;
18280 }
18281
18282 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18283
18284 bool
18285 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18286   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18287     return false;
18288
18289   VT = VT.getScalarType();
18290
18291   if (!VT.isSimple())
18292     return false;
18293
18294   switch (VT.getSimpleVT().SimpleTy) {
18295   case MVT::f32:
18296   case MVT::f64:
18297     return true;
18298   default:
18299     break;
18300   }
18301
18302   return false;
18303 }
18304
18305 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18306   // i16 instructions are longer (0x66 prefix) and potentially slower.
18307   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18308 }
18309
18310 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18311 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18312 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18313 /// are assumed to be legal.
18314 bool
18315 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18316                                       EVT VT) const {
18317   if (!VT.isSimple())
18318     return false;
18319
18320   // Not for i1 vectors
18321   if (VT.getScalarType() == MVT::i1)
18322     return false;
18323
18324   // Very little shuffling can be done for 64-bit vectors right now.
18325   if (VT.getSizeInBits() == 64)
18326     return false;
18327
18328   // We only care that the types being shuffled are legal. The lowering can
18329   // handle any possible shuffle mask that results.
18330   return isTypeLegal(VT.getSimpleVT());
18331 }
18332
18333 bool
18334 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18335                                           EVT VT) const {
18336   // Just delegate to the generic legality, clear masks aren't special.
18337   return isShuffleMaskLegal(Mask, VT);
18338 }
18339
18340 //===----------------------------------------------------------------------===//
18341 //                           X86 Scheduler Hooks
18342 //===----------------------------------------------------------------------===//
18343
18344 /// Utility function to emit xbegin specifying the start of an RTM region.
18345 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18346                                      const TargetInstrInfo *TII) {
18347   DebugLoc DL = MI->getDebugLoc();
18348
18349   const BasicBlock *BB = MBB->getBasicBlock();
18350   MachineFunction::iterator I = MBB;
18351   ++I;
18352
18353   // For the v = xbegin(), we generate
18354   //
18355   // thisMBB:
18356   //  xbegin sinkMBB
18357   //
18358   // mainMBB:
18359   //  eax = -1
18360   //
18361   // sinkMBB:
18362   //  v = eax
18363
18364   MachineBasicBlock *thisMBB = MBB;
18365   MachineFunction *MF = MBB->getParent();
18366   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18367   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18368   MF->insert(I, mainMBB);
18369   MF->insert(I, sinkMBB);
18370
18371   // Transfer the remainder of BB and its successor edges to sinkMBB.
18372   sinkMBB->splice(sinkMBB->begin(), MBB,
18373                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18374   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18375
18376   // thisMBB:
18377   //  xbegin sinkMBB
18378   //  # fallthrough to mainMBB
18379   //  # abortion to sinkMBB
18380   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18381   thisMBB->addSuccessor(mainMBB);
18382   thisMBB->addSuccessor(sinkMBB);
18383
18384   // mainMBB:
18385   //  EAX = -1
18386   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18387   mainMBB->addSuccessor(sinkMBB);
18388
18389   // sinkMBB:
18390   // EAX is live into the sinkMBB
18391   sinkMBB->addLiveIn(X86::EAX);
18392   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18393           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18394     .addReg(X86::EAX);
18395
18396   MI->eraseFromParent();
18397   return sinkMBB;
18398 }
18399
18400 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18401 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18402 // in the .td file.
18403 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18404                                        const TargetInstrInfo *TII) {
18405   unsigned Opc;
18406   switch (MI->getOpcode()) {
18407   default: llvm_unreachable("illegal opcode!");
18408   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18409   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18410   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18411   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18412   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18413   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18414   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18415   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18416   }
18417
18418   DebugLoc dl = MI->getDebugLoc();
18419   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18420
18421   unsigned NumArgs = MI->getNumOperands();
18422   for (unsigned i = 1; i < NumArgs; ++i) {
18423     MachineOperand &Op = MI->getOperand(i);
18424     if (!(Op.isReg() && Op.isImplicit()))
18425       MIB.addOperand(Op);
18426   }
18427   if (MI->hasOneMemOperand())
18428     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18429
18430   BuildMI(*BB, MI, dl,
18431     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18432     .addReg(X86::XMM0);
18433
18434   MI->eraseFromParent();
18435   return BB;
18436 }
18437
18438 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18439 // defs in an instruction pattern
18440 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18441                                        const TargetInstrInfo *TII) {
18442   unsigned Opc;
18443   switch (MI->getOpcode()) {
18444   default: llvm_unreachable("illegal opcode!");
18445   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18446   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18447   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18448   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18449   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18450   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18451   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18452   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18453   }
18454
18455   DebugLoc dl = MI->getDebugLoc();
18456   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18457
18458   unsigned NumArgs = MI->getNumOperands(); // remove the results
18459   for (unsigned i = 1; i < NumArgs; ++i) {
18460     MachineOperand &Op = MI->getOperand(i);
18461     if (!(Op.isReg() && Op.isImplicit()))
18462       MIB.addOperand(Op);
18463   }
18464   if (MI->hasOneMemOperand())
18465     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18466
18467   BuildMI(*BB, MI, dl,
18468     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18469     .addReg(X86::ECX);
18470
18471   MI->eraseFromParent();
18472   return BB;
18473 }
18474
18475 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18476                                       const X86Subtarget *Subtarget) {
18477   DebugLoc dl = MI->getDebugLoc();
18478   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18479   // Address into RAX/EAX, other two args into ECX, EDX.
18480   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18481   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18482   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18483   for (int i = 0; i < X86::AddrNumOperands; ++i)
18484     MIB.addOperand(MI->getOperand(i));
18485
18486   unsigned ValOps = X86::AddrNumOperands;
18487   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18488     .addReg(MI->getOperand(ValOps).getReg());
18489   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18490     .addReg(MI->getOperand(ValOps+1).getReg());
18491
18492   // The instruction doesn't actually take any operands though.
18493   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18494
18495   MI->eraseFromParent(); // The pseudo is gone now.
18496   return BB;
18497 }
18498
18499 MachineBasicBlock *
18500 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18501                                                  MachineBasicBlock *MBB) const {
18502   // Emit va_arg instruction on X86-64.
18503
18504   // Operands to this pseudo-instruction:
18505   // 0  ) Output        : destination address (reg)
18506   // 1-5) Input         : va_list address (addr, i64mem)
18507   // 6  ) ArgSize       : Size (in bytes) of vararg type
18508   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18509   // 8  ) Align         : Alignment of type
18510   // 9  ) EFLAGS (implicit-def)
18511
18512   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18513   static_assert(X86::AddrNumOperands == 5,
18514                 "VAARG_64 assumes 5 address operands");
18515
18516   unsigned DestReg = MI->getOperand(0).getReg();
18517   MachineOperand &Base = MI->getOperand(1);
18518   MachineOperand &Scale = MI->getOperand(2);
18519   MachineOperand &Index = MI->getOperand(3);
18520   MachineOperand &Disp = MI->getOperand(4);
18521   MachineOperand &Segment = MI->getOperand(5);
18522   unsigned ArgSize = MI->getOperand(6).getImm();
18523   unsigned ArgMode = MI->getOperand(7).getImm();
18524   unsigned Align = MI->getOperand(8).getImm();
18525
18526   // Memory Reference
18527   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18528   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18529   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18530
18531   // Machine Information
18532   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18533   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18534   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18535   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18536   DebugLoc DL = MI->getDebugLoc();
18537
18538   // struct va_list {
18539   //   i32   gp_offset
18540   //   i32   fp_offset
18541   //   i64   overflow_area (address)
18542   //   i64   reg_save_area (address)
18543   // }
18544   // sizeof(va_list) = 24
18545   // alignment(va_list) = 8
18546
18547   unsigned TotalNumIntRegs = 6;
18548   unsigned TotalNumXMMRegs = 8;
18549   bool UseGPOffset = (ArgMode == 1);
18550   bool UseFPOffset = (ArgMode == 2);
18551   unsigned MaxOffset = TotalNumIntRegs * 8 +
18552                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18553
18554   /* Align ArgSize to a multiple of 8 */
18555   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18556   bool NeedsAlign = (Align > 8);
18557
18558   MachineBasicBlock *thisMBB = MBB;
18559   MachineBasicBlock *overflowMBB;
18560   MachineBasicBlock *offsetMBB;
18561   MachineBasicBlock *endMBB;
18562
18563   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18564   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18565   unsigned OffsetReg = 0;
18566
18567   if (!UseGPOffset && !UseFPOffset) {
18568     // If we only pull from the overflow region, we don't create a branch.
18569     // We don't need to alter control flow.
18570     OffsetDestReg = 0; // unused
18571     OverflowDestReg = DestReg;
18572
18573     offsetMBB = nullptr;
18574     overflowMBB = thisMBB;
18575     endMBB = thisMBB;
18576   } else {
18577     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18578     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18579     // If not, pull from overflow_area. (branch to overflowMBB)
18580     //
18581     //       thisMBB
18582     //         |     .
18583     //         |        .
18584     //     offsetMBB   overflowMBB
18585     //         |        .
18586     //         |     .
18587     //        endMBB
18588
18589     // Registers for the PHI in endMBB
18590     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18591     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18592
18593     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18594     MachineFunction *MF = MBB->getParent();
18595     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18596     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18597     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18598
18599     MachineFunction::iterator MBBIter = MBB;
18600     ++MBBIter;
18601
18602     // Insert the new basic blocks
18603     MF->insert(MBBIter, offsetMBB);
18604     MF->insert(MBBIter, overflowMBB);
18605     MF->insert(MBBIter, endMBB);
18606
18607     // Transfer the remainder of MBB and its successor edges to endMBB.
18608     endMBB->splice(endMBB->begin(), thisMBB,
18609                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18610     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18611
18612     // Make offsetMBB and overflowMBB successors of thisMBB
18613     thisMBB->addSuccessor(offsetMBB);
18614     thisMBB->addSuccessor(overflowMBB);
18615
18616     // endMBB is a successor of both offsetMBB and overflowMBB
18617     offsetMBB->addSuccessor(endMBB);
18618     overflowMBB->addSuccessor(endMBB);
18619
18620     // Load the offset value into a register
18621     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18622     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18623       .addOperand(Base)
18624       .addOperand(Scale)
18625       .addOperand(Index)
18626       .addDisp(Disp, UseFPOffset ? 4 : 0)
18627       .addOperand(Segment)
18628       .setMemRefs(MMOBegin, MMOEnd);
18629
18630     // Check if there is enough room left to pull this argument.
18631     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18632       .addReg(OffsetReg)
18633       .addImm(MaxOffset + 8 - ArgSizeA8);
18634
18635     // Branch to "overflowMBB" if offset >= max
18636     // Fall through to "offsetMBB" otherwise
18637     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18638       .addMBB(overflowMBB);
18639   }
18640
18641   // In offsetMBB, emit code to use the reg_save_area.
18642   if (offsetMBB) {
18643     assert(OffsetReg != 0);
18644
18645     // Read the reg_save_area address.
18646     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18647     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18648       .addOperand(Base)
18649       .addOperand(Scale)
18650       .addOperand(Index)
18651       .addDisp(Disp, 16)
18652       .addOperand(Segment)
18653       .setMemRefs(MMOBegin, MMOEnd);
18654
18655     // Zero-extend the offset
18656     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18657       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18658         .addImm(0)
18659         .addReg(OffsetReg)
18660         .addImm(X86::sub_32bit);
18661
18662     // Add the offset to the reg_save_area to get the final address.
18663     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18664       .addReg(OffsetReg64)
18665       .addReg(RegSaveReg);
18666
18667     // Compute the offset for the next argument
18668     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18669     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18670       .addReg(OffsetReg)
18671       .addImm(UseFPOffset ? 16 : 8);
18672
18673     // Store it back into the va_list.
18674     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18675       .addOperand(Base)
18676       .addOperand(Scale)
18677       .addOperand(Index)
18678       .addDisp(Disp, UseFPOffset ? 4 : 0)
18679       .addOperand(Segment)
18680       .addReg(NextOffsetReg)
18681       .setMemRefs(MMOBegin, MMOEnd);
18682
18683     // Jump to endMBB
18684     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18685       .addMBB(endMBB);
18686   }
18687
18688   //
18689   // Emit code to use overflow area
18690   //
18691
18692   // Load the overflow_area address into a register.
18693   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18694   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18695     .addOperand(Base)
18696     .addOperand(Scale)
18697     .addOperand(Index)
18698     .addDisp(Disp, 8)
18699     .addOperand(Segment)
18700     .setMemRefs(MMOBegin, MMOEnd);
18701
18702   // If we need to align it, do so. Otherwise, just copy the address
18703   // to OverflowDestReg.
18704   if (NeedsAlign) {
18705     // Align the overflow address
18706     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18707     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18708
18709     // aligned_addr = (addr + (align-1)) & ~(align-1)
18710     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18711       .addReg(OverflowAddrReg)
18712       .addImm(Align-1);
18713
18714     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18715       .addReg(TmpReg)
18716       .addImm(~(uint64_t)(Align-1));
18717   } else {
18718     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18719       .addReg(OverflowAddrReg);
18720   }
18721
18722   // Compute the next overflow address after this argument.
18723   // (the overflow address should be kept 8-byte aligned)
18724   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18725   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18726     .addReg(OverflowDestReg)
18727     .addImm(ArgSizeA8);
18728
18729   // Store the new overflow address.
18730   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18731     .addOperand(Base)
18732     .addOperand(Scale)
18733     .addOperand(Index)
18734     .addDisp(Disp, 8)
18735     .addOperand(Segment)
18736     .addReg(NextAddrReg)
18737     .setMemRefs(MMOBegin, MMOEnd);
18738
18739   // If we branched, emit the PHI to the front of endMBB.
18740   if (offsetMBB) {
18741     BuildMI(*endMBB, endMBB->begin(), DL,
18742             TII->get(X86::PHI), DestReg)
18743       .addReg(OffsetDestReg).addMBB(offsetMBB)
18744       .addReg(OverflowDestReg).addMBB(overflowMBB);
18745   }
18746
18747   // Erase the pseudo instruction
18748   MI->eraseFromParent();
18749
18750   return endMBB;
18751 }
18752
18753 MachineBasicBlock *
18754 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18755                                                  MachineInstr *MI,
18756                                                  MachineBasicBlock *MBB) const {
18757   // Emit code to save XMM registers to the stack. The ABI says that the
18758   // number of registers to save is given in %al, so it's theoretically
18759   // possible to do an indirect jump trick to avoid saving all of them,
18760   // however this code takes a simpler approach and just executes all
18761   // of the stores if %al is non-zero. It's less code, and it's probably
18762   // easier on the hardware branch predictor, and stores aren't all that
18763   // expensive anyway.
18764
18765   // Create the new basic blocks. One block contains all the XMM stores,
18766   // and one block is the final destination regardless of whether any
18767   // stores were performed.
18768   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18769   MachineFunction *F = MBB->getParent();
18770   MachineFunction::iterator MBBIter = MBB;
18771   ++MBBIter;
18772   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18773   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18774   F->insert(MBBIter, XMMSaveMBB);
18775   F->insert(MBBIter, EndMBB);
18776
18777   // Transfer the remainder of MBB and its successor edges to EndMBB.
18778   EndMBB->splice(EndMBB->begin(), MBB,
18779                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18780   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18781
18782   // The original block will now fall through to the XMM save block.
18783   MBB->addSuccessor(XMMSaveMBB);
18784   // The XMMSaveMBB will fall through to the end block.
18785   XMMSaveMBB->addSuccessor(EndMBB);
18786
18787   // Now add the instructions.
18788   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18789   DebugLoc DL = MI->getDebugLoc();
18790
18791   unsigned CountReg = MI->getOperand(0).getReg();
18792   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18793   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18794
18795   if (!Subtarget->isTargetWin64()) {
18796     // If %al is 0, branch around the XMM save block.
18797     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18798     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18799     MBB->addSuccessor(EndMBB);
18800   }
18801
18802   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18803   // that was just emitted, but clearly shouldn't be "saved".
18804   assert((MI->getNumOperands() <= 3 ||
18805           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18806           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18807          && "Expected last argument to be EFLAGS");
18808   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18809   // In the XMM save block, save all the XMM argument registers.
18810   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18811     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18812     MachineMemOperand *MMO =
18813       F->getMachineMemOperand(
18814           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18815         MachineMemOperand::MOStore,
18816         /*Size=*/16, /*Align=*/16);
18817     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18818       .addFrameIndex(RegSaveFrameIndex)
18819       .addImm(/*Scale=*/1)
18820       .addReg(/*IndexReg=*/0)
18821       .addImm(/*Disp=*/Offset)
18822       .addReg(/*Segment=*/0)
18823       .addReg(MI->getOperand(i).getReg())
18824       .addMemOperand(MMO);
18825   }
18826
18827   MI->eraseFromParent();   // The pseudo instruction is gone now.
18828
18829   return EndMBB;
18830 }
18831
18832 // The EFLAGS operand of SelectItr might be missing a kill marker
18833 // because there were multiple uses of EFLAGS, and ISel didn't know
18834 // which to mark. Figure out whether SelectItr should have had a
18835 // kill marker, and set it if it should. Returns the correct kill
18836 // marker value.
18837 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18838                                      MachineBasicBlock* BB,
18839                                      const TargetRegisterInfo* TRI) {
18840   // Scan forward through BB for a use/def of EFLAGS.
18841   MachineBasicBlock::iterator miI(std::next(SelectItr));
18842   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18843     const MachineInstr& mi = *miI;
18844     if (mi.readsRegister(X86::EFLAGS))
18845       return false;
18846     if (mi.definesRegister(X86::EFLAGS))
18847       break; // Should have kill-flag - update below.
18848   }
18849
18850   // If we hit the end of the block, check whether EFLAGS is live into a
18851   // successor.
18852   if (miI == BB->end()) {
18853     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18854                                           sEnd = BB->succ_end();
18855          sItr != sEnd; ++sItr) {
18856       MachineBasicBlock* succ = *sItr;
18857       if (succ->isLiveIn(X86::EFLAGS))
18858         return false;
18859     }
18860   }
18861
18862   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18863   // out. SelectMI should have a kill flag on EFLAGS.
18864   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18865   return true;
18866 }
18867
18868 MachineBasicBlock *
18869 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18870                                      MachineBasicBlock *BB) const {
18871   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18872   DebugLoc DL = MI->getDebugLoc();
18873
18874   // To "insert" a SELECT_CC instruction, we actually have to insert the
18875   // diamond control-flow pattern.  The incoming instruction knows the
18876   // destination vreg to set, the condition code register to branch on, the
18877   // true/false values to select between, and a branch opcode to use.
18878   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18879   MachineFunction::iterator It = BB;
18880   ++It;
18881
18882   //  thisMBB:
18883   //  ...
18884   //   TrueVal = ...
18885   //   cmpTY ccX, r1, r2
18886   //   bCC copy1MBB
18887   //   fallthrough --> copy0MBB
18888   MachineBasicBlock *thisMBB = BB;
18889   MachineFunction *F = BB->getParent();
18890
18891   // We also lower double CMOVs:
18892   //   (CMOV (CMOV F, T, cc1), T, cc2)
18893   // to two successives branches.  For that, we look for another CMOV as the
18894   // following instruction.
18895   //
18896   // Without this, we would add a PHI between the two jumps, which ends up
18897   // creating a few copies all around. For instance, for
18898   //
18899   //    (sitofp (zext (fcmp une)))
18900   //
18901   // we would generate:
18902   //
18903   //         ucomiss %xmm1, %xmm0
18904   //         movss  <1.0f>, %xmm0
18905   //         movaps  %xmm0, %xmm1
18906   //         jne     .LBB5_2
18907   //         xorps   %xmm1, %xmm1
18908   // .LBB5_2:
18909   //         jp      .LBB5_4
18910   //         movaps  %xmm1, %xmm0
18911   // .LBB5_4:
18912   //         retq
18913   //
18914   // because this custom-inserter would have generated:
18915   //
18916   //   A
18917   //   | \
18918   //   |  B
18919   //   | /
18920   //   C
18921   //   | \
18922   //   |  D
18923   //   | /
18924   //   E
18925   //
18926   // A: X = ...; Y = ...
18927   // B: empty
18928   // C: Z = PHI [X, A], [Y, B]
18929   // D: empty
18930   // E: PHI [X, C], [Z, D]
18931   //
18932   // If we lower both CMOVs in a single step, we can instead generate:
18933   //
18934   //   A
18935   //   | \
18936   //   |  C
18937   //   | /|
18938   //   |/ |
18939   //   |  |
18940   //   |  D
18941   //   | /
18942   //   E
18943   //
18944   // A: X = ...; Y = ...
18945   // D: empty
18946   // E: PHI [X, A], [X, C], [Y, D]
18947   //
18948   // Which, in our sitofp/fcmp example, gives us something like:
18949   //
18950   //         ucomiss %xmm1, %xmm0
18951   //         movss  <1.0f>, %xmm0
18952   //         jne     .LBB5_4
18953   //         jp      .LBB5_4
18954   //         xorps   %xmm0, %xmm0
18955   // .LBB5_4:
18956   //         retq
18957   //
18958   MachineInstr *NextCMOV = nullptr;
18959   MachineBasicBlock::iterator NextMIIt =
18960       std::next(MachineBasicBlock::iterator(MI));
18961   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18962       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18963       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18964     NextCMOV = &*NextMIIt;
18965
18966   MachineBasicBlock *jcc1MBB = nullptr;
18967
18968   // If we have a double CMOV, we lower it to two successive branches to
18969   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18970   if (NextCMOV) {
18971     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18972     F->insert(It, jcc1MBB);
18973     jcc1MBB->addLiveIn(X86::EFLAGS);
18974   }
18975
18976   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18977   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18978   F->insert(It, copy0MBB);
18979   F->insert(It, sinkMBB);
18980
18981   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18982   // live into the sink and copy blocks.
18983   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18984
18985   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18986   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18987       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18988     copy0MBB->addLiveIn(X86::EFLAGS);
18989     sinkMBB->addLiveIn(X86::EFLAGS);
18990   }
18991
18992   // Transfer the remainder of BB and its successor edges to sinkMBB.
18993   sinkMBB->splice(sinkMBB->begin(), BB,
18994                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18995   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18996
18997   // Add the true and fallthrough blocks as its successors.
18998   if (NextCMOV) {
18999     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19000     BB->addSuccessor(jcc1MBB);
19001
19002     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19003     // jump to the sinkMBB.
19004     jcc1MBB->addSuccessor(copy0MBB);
19005     jcc1MBB->addSuccessor(sinkMBB);
19006   } else {
19007     BB->addSuccessor(copy0MBB);
19008   }
19009
19010   // The true block target of the first (or only) branch is always sinkMBB.
19011   BB->addSuccessor(sinkMBB);
19012
19013   // Create the conditional branch instruction.
19014   unsigned Opc =
19015     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19016   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19017
19018   if (NextCMOV) {
19019     unsigned Opc2 = X86::GetCondBranchFromCond(
19020         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19021     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19022   }
19023
19024   //  copy0MBB:
19025   //   %FalseValue = ...
19026   //   # fallthrough to sinkMBB
19027   copy0MBB->addSuccessor(sinkMBB);
19028
19029   //  sinkMBB:
19030   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19031   //  ...
19032   MachineInstrBuilder MIB =
19033       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19034               MI->getOperand(0).getReg())
19035           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19036           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19037
19038   // If we have a double CMOV, the second Jcc provides the same incoming
19039   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19040   if (NextCMOV) {
19041     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19042     // Copy the PHI result to the register defined by the second CMOV.
19043     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19044             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19045         .addReg(MI->getOperand(0).getReg());
19046     NextCMOV->eraseFromParent();
19047   }
19048
19049   MI->eraseFromParent();   // The pseudo instruction is gone now.
19050   return sinkMBB;
19051 }
19052
19053 MachineBasicBlock *
19054 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19055                                         MachineBasicBlock *BB) const {
19056   MachineFunction *MF = BB->getParent();
19057   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19058   DebugLoc DL = MI->getDebugLoc();
19059   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19060
19061   assert(MF->shouldSplitStack());
19062
19063   const bool Is64Bit = Subtarget->is64Bit();
19064   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19065
19066   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19067   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19068
19069   // BB:
19070   //  ... [Till the alloca]
19071   // If stacklet is not large enough, jump to mallocMBB
19072   //
19073   // bumpMBB:
19074   //  Allocate by subtracting from RSP
19075   //  Jump to continueMBB
19076   //
19077   // mallocMBB:
19078   //  Allocate by call to runtime
19079   //
19080   // continueMBB:
19081   //  ...
19082   //  [rest of original BB]
19083   //
19084
19085   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19086   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19087   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19088
19089   MachineRegisterInfo &MRI = MF->getRegInfo();
19090   const TargetRegisterClass *AddrRegClass =
19091     getRegClassFor(getPointerTy());
19092
19093   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19094     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19095     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19096     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19097     sizeVReg = MI->getOperand(1).getReg(),
19098     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19099
19100   MachineFunction::iterator MBBIter = BB;
19101   ++MBBIter;
19102
19103   MF->insert(MBBIter, bumpMBB);
19104   MF->insert(MBBIter, mallocMBB);
19105   MF->insert(MBBIter, continueMBB);
19106
19107   continueMBB->splice(continueMBB->begin(), BB,
19108                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19109   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19110
19111   // Add code to the main basic block to check if the stack limit has been hit,
19112   // and if so, jump to mallocMBB otherwise to bumpMBB.
19113   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19114   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19115     .addReg(tmpSPVReg).addReg(sizeVReg);
19116   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19117     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19118     .addReg(SPLimitVReg);
19119   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19120
19121   // bumpMBB simply decreases the stack pointer, since we know the current
19122   // stacklet has enough space.
19123   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19124     .addReg(SPLimitVReg);
19125   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19126     .addReg(SPLimitVReg);
19127   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19128
19129   // Calls into a routine in libgcc to allocate more space from the heap.
19130   const uint32_t *RegMask =
19131       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19132   if (IsLP64) {
19133     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19134       .addReg(sizeVReg);
19135     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19136       .addExternalSymbol("__morestack_allocate_stack_space")
19137       .addRegMask(RegMask)
19138       .addReg(X86::RDI, RegState::Implicit)
19139       .addReg(X86::RAX, RegState::ImplicitDefine);
19140   } else if (Is64Bit) {
19141     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19142       .addReg(sizeVReg);
19143     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19144       .addExternalSymbol("__morestack_allocate_stack_space")
19145       .addRegMask(RegMask)
19146       .addReg(X86::EDI, RegState::Implicit)
19147       .addReg(X86::EAX, RegState::ImplicitDefine);
19148   } else {
19149     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19150       .addImm(12);
19151     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19152     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19153       .addExternalSymbol("__morestack_allocate_stack_space")
19154       .addRegMask(RegMask)
19155       .addReg(X86::EAX, RegState::ImplicitDefine);
19156   }
19157
19158   if (!Is64Bit)
19159     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19160       .addImm(16);
19161
19162   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19163     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19164   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19165
19166   // Set up the CFG correctly.
19167   BB->addSuccessor(bumpMBB);
19168   BB->addSuccessor(mallocMBB);
19169   mallocMBB->addSuccessor(continueMBB);
19170   bumpMBB->addSuccessor(continueMBB);
19171
19172   // Take care of the PHI nodes.
19173   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19174           MI->getOperand(0).getReg())
19175     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19176     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19177
19178   // Delete the original pseudo instruction.
19179   MI->eraseFromParent();
19180
19181   // And we're done.
19182   return continueMBB;
19183 }
19184
19185 MachineBasicBlock *
19186 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19187                                         MachineBasicBlock *BB) const {
19188   DebugLoc DL = MI->getDebugLoc();
19189
19190   assert(!Subtarget->isTargetMachO());
19191
19192   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19193
19194   MI->eraseFromParent();   // The pseudo instruction is gone now.
19195   return BB;
19196 }
19197
19198 MachineBasicBlock *
19199 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19200                                       MachineBasicBlock *BB) const {
19201   // This is pretty easy.  We're taking the value that we received from
19202   // our load from the relocation, sticking it in either RDI (x86-64)
19203   // or EAX and doing an indirect call.  The return value will then
19204   // be in the normal return register.
19205   MachineFunction *F = BB->getParent();
19206   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19207   DebugLoc DL = MI->getDebugLoc();
19208
19209   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19210   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19211
19212   // Get a register mask for the lowered call.
19213   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19214   // proper register mask.
19215   const uint32_t *RegMask =
19216       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19217   if (Subtarget->is64Bit()) {
19218     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19219                                       TII->get(X86::MOV64rm), X86::RDI)
19220     .addReg(X86::RIP)
19221     .addImm(0).addReg(0)
19222     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19223                       MI->getOperand(3).getTargetFlags())
19224     .addReg(0);
19225     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19226     addDirectMem(MIB, X86::RDI);
19227     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19228   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19229     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19230                                       TII->get(X86::MOV32rm), X86::EAX)
19231     .addReg(0)
19232     .addImm(0).addReg(0)
19233     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19234                       MI->getOperand(3).getTargetFlags())
19235     .addReg(0);
19236     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19237     addDirectMem(MIB, X86::EAX);
19238     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19239   } else {
19240     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19241                                       TII->get(X86::MOV32rm), X86::EAX)
19242     .addReg(TII->getGlobalBaseReg(F))
19243     .addImm(0).addReg(0)
19244     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19245                       MI->getOperand(3).getTargetFlags())
19246     .addReg(0);
19247     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19248     addDirectMem(MIB, X86::EAX);
19249     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19250   }
19251
19252   MI->eraseFromParent(); // The pseudo instruction is gone now.
19253   return BB;
19254 }
19255
19256 MachineBasicBlock *
19257 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19258                                     MachineBasicBlock *MBB) const {
19259   DebugLoc DL = MI->getDebugLoc();
19260   MachineFunction *MF = MBB->getParent();
19261   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19262   MachineRegisterInfo &MRI = MF->getRegInfo();
19263
19264   const BasicBlock *BB = MBB->getBasicBlock();
19265   MachineFunction::iterator I = MBB;
19266   ++I;
19267
19268   // Memory Reference
19269   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19270   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19271
19272   unsigned DstReg;
19273   unsigned MemOpndSlot = 0;
19274
19275   unsigned CurOp = 0;
19276
19277   DstReg = MI->getOperand(CurOp++).getReg();
19278   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19279   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19280   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19281   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19282
19283   MemOpndSlot = CurOp;
19284
19285   MVT PVT = getPointerTy();
19286   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19287          "Invalid Pointer Size!");
19288
19289   // For v = setjmp(buf), we generate
19290   //
19291   // thisMBB:
19292   //  buf[LabelOffset] = restoreMBB
19293   //  SjLjSetup restoreMBB
19294   //
19295   // mainMBB:
19296   //  v_main = 0
19297   //
19298   // sinkMBB:
19299   //  v = phi(main, restore)
19300   //
19301   // restoreMBB:
19302   //  if base pointer being used, load it from frame
19303   //  v_restore = 1
19304
19305   MachineBasicBlock *thisMBB = MBB;
19306   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19307   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19308   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19309   MF->insert(I, mainMBB);
19310   MF->insert(I, sinkMBB);
19311   MF->push_back(restoreMBB);
19312
19313   MachineInstrBuilder MIB;
19314
19315   // Transfer the remainder of BB and its successor edges to sinkMBB.
19316   sinkMBB->splice(sinkMBB->begin(), MBB,
19317                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19318   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19319
19320   // thisMBB:
19321   unsigned PtrStoreOpc = 0;
19322   unsigned LabelReg = 0;
19323   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19324   Reloc::Model RM = MF->getTarget().getRelocationModel();
19325   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19326                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19327
19328   // Prepare IP either in reg or imm.
19329   if (!UseImmLabel) {
19330     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19331     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19332     LabelReg = MRI.createVirtualRegister(PtrRC);
19333     if (Subtarget->is64Bit()) {
19334       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19335               .addReg(X86::RIP)
19336               .addImm(0)
19337               .addReg(0)
19338               .addMBB(restoreMBB)
19339               .addReg(0);
19340     } else {
19341       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19342       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19343               .addReg(XII->getGlobalBaseReg(MF))
19344               .addImm(0)
19345               .addReg(0)
19346               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19347               .addReg(0);
19348     }
19349   } else
19350     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19351   // Store IP
19352   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19353   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19354     if (i == X86::AddrDisp)
19355       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19356     else
19357       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19358   }
19359   if (!UseImmLabel)
19360     MIB.addReg(LabelReg);
19361   else
19362     MIB.addMBB(restoreMBB);
19363   MIB.setMemRefs(MMOBegin, MMOEnd);
19364   // Setup
19365   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19366           .addMBB(restoreMBB);
19367
19368   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19369   MIB.addRegMask(RegInfo->getNoPreservedMask());
19370   thisMBB->addSuccessor(mainMBB);
19371   thisMBB->addSuccessor(restoreMBB);
19372
19373   // mainMBB:
19374   //  EAX = 0
19375   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19376   mainMBB->addSuccessor(sinkMBB);
19377
19378   // sinkMBB:
19379   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19380           TII->get(X86::PHI), DstReg)
19381     .addReg(mainDstReg).addMBB(mainMBB)
19382     .addReg(restoreDstReg).addMBB(restoreMBB);
19383
19384   // restoreMBB:
19385   if (RegInfo->hasBasePointer(*MF)) {
19386     const bool Uses64BitFramePtr =
19387         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19388     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19389     X86FI->setRestoreBasePointer(MF);
19390     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19391     unsigned BasePtr = RegInfo->getBaseRegister();
19392     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19393     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19394                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19395       .setMIFlag(MachineInstr::FrameSetup);
19396   }
19397   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19398   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19399   restoreMBB->addSuccessor(sinkMBB);
19400
19401   MI->eraseFromParent();
19402   return sinkMBB;
19403 }
19404
19405 MachineBasicBlock *
19406 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19407                                      MachineBasicBlock *MBB) const {
19408   DebugLoc DL = MI->getDebugLoc();
19409   MachineFunction *MF = MBB->getParent();
19410   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19411   MachineRegisterInfo &MRI = MF->getRegInfo();
19412
19413   // Memory Reference
19414   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19415   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19416
19417   MVT PVT = getPointerTy();
19418   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19419          "Invalid Pointer Size!");
19420
19421   const TargetRegisterClass *RC =
19422     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19423   unsigned Tmp = MRI.createVirtualRegister(RC);
19424   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19425   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19426   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19427   unsigned SP = RegInfo->getStackRegister();
19428
19429   MachineInstrBuilder MIB;
19430
19431   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19432   const int64_t SPOffset = 2 * PVT.getStoreSize();
19433
19434   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19435   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19436
19437   // Reload FP
19438   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19439   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19440     MIB.addOperand(MI->getOperand(i));
19441   MIB.setMemRefs(MMOBegin, MMOEnd);
19442   // Reload IP
19443   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19444   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19445     if (i == X86::AddrDisp)
19446       MIB.addDisp(MI->getOperand(i), LabelOffset);
19447     else
19448       MIB.addOperand(MI->getOperand(i));
19449   }
19450   MIB.setMemRefs(MMOBegin, MMOEnd);
19451   // Reload SP
19452   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19453   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19454     if (i == X86::AddrDisp)
19455       MIB.addDisp(MI->getOperand(i), SPOffset);
19456     else
19457       MIB.addOperand(MI->getOperand(i));
19458   }
19459   MIB.setMemRefs(MMOBegin, MMOEnd);
19460   // Jump
19461   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19462
19463   MI->eraseFromParent();
19464   return MBB;
19465 }
19466
19467 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19468 // accumulator loops. Writing back to the accumulator allows the coalescer
19469 // to remove extra copies in the loop.
19470 MachineBasicBlock *
19471 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19472                                  MachineBasicBlock *MBB) const {
19473   MachineOperand &AddendOp = MI->getOperand(3);
19474
19475   // Bail out early if the addend isn't a register - we can't switch these.
19476   if (!AddendOp.isReg())
19477     return MBB;
19478
19479   MachineFunction &MF = *MBB->getParent();
19480   MachineRegisterInfo &MRI = MF.getRegInfo();
19481
19482   // Check whether the addend is defined by a PHI:
19483   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19484   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19485   if (!AddendDef.isPHI())
19486     return MBB;
19487
19488   // Look for the following pattern:
19489   // loop:
19490   //   %addend = phi [%entry, 0], [%loop, %result]
19491   //   ...
19492   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19493
19494   // Replace with:
19495   //   loop:
19496   //   %addend = phi [%entry, 0], [%loop, %result]
19497   //   ...
19498   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19499
19500   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19501     assert(AddendDef.getOperand(i).isReg());
19502     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19503     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19504     if (&PHISrcInst == MI) {
19505       // Found a matching instruction.
19506       unsigned NewFMAOpc = 0;
19507       switch (MI->getOpcode()) {
19508         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19509         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19510         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19511         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19512         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19513         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19514         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19515         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19516         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19517         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19518         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19519         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19520         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19521         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19522         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19523         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19524         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19525         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19526         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19527         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19528
19529         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19530         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19531         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19532         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19533         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19534         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19535         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19536         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19537         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19538         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19539         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19540         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19541         default: llvm_unreachable("Unrecognized FMA variant.");
19542       }
19543
19544       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19545       MachineInstrBuilder MIB =
19546         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19547         .addOperand(MI->getOperand(0))
19548         .addOperand(MI->getOperand(3))
19549         .addOperand(MI->getOperand(2))
19550         .addOperand(MI->getOperand(1));
19551       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19552       MI->eraseFromParent();
19553     }
19554   }
19555
19556   return MBB;
19557 }
19558
19559 MachineBasicBlock *
19560 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19561                                                MachineBasicBlock *BB) const {
19562   switch (MI->getOpcode()) {
19563   default: llvm_unreachable("Unexpected instr type to insert");
19564   case X86::TAILJMPd64:
19565   case X86::TAILJMPr64:
19566   case X86::TAILJMPm64:
19567   case X86::TAILJMPd64_REX:
19568   case X86::TAILJMPr64_REX:
19569   case X86::TAILJMPm64_REX:
19570     llvm_unreachable("TAILJMP64 would not be touched here.");
19571   case X86::TCRETURNdi64:
19572   case X86::TCRETURNri64:
19573   case X86::TCRETURNmi64:
19574     return BB;
19575   case X86::WIN_ALLOCA:
19576     return EmitLoweredWinAlloca(MI, BB);
19577   case X86::SEG_ALLOCA_32:
19578   case X86::SEG_ALLOCA_64:
19579     return EmitLoweredSegAlloca(MI, BB);
19580   case X86::TLSCall_32:
19581   case X86::TLSCall_64:
19582     return EmitLoweredTLSCall(MI, BB);
19583   case X86::CMOV_GR8:
19584   case X86::CMOV_FR32:
19585   case X86::CMOV_FR64:
19586   case X86::CMOV_V4F32:
19587   case X86::CMOV_V2F64:
19588   case X86::CMOV_V2I64:
19589   case X86::CMOV_V8F32:
19590   case X86::CMOV_V4F64:
19591   case X86::CMOV_V4I64:
19592   case X86::CMOV_V16F32:
19593   case X86::CMOV_V8F64:
19594   case X86::CMOV_V8I64:
19595   case X86::CMOV_GR16:
19596   case X86::CMOV_GR32:
19597   case X86::CMOV_RFP32:
19598   case X86::CMOV_RFP64:
19599   case X86::CMOV_RFP80:
19600   case X86::CMOV_V8I1:
19601   case X86::CMOV_V16I1:
19602   case X86::CMOV_V32I1:
19603   case X86::CMOV_V64I1:
19604     return EmitLoweredSelect(MI, BB);
19605
19606   case X86::FP32_TO_INT16_IN_MEM:
19607   case X86::FP32_TO_INT32_IN_MEM:
19608   case X86::FP32_TO_INT64_IN_MEM:
19609   case X86::FP64_TO_INT16_IN_MEM:
19610   case X86::FP64_TO_INT32_IN_MEM:
19611   case X86::FP64_TO_INT64_IN_MEM:
19612   case X86::FP80_TO_INT16_IN_MEM:
19613   case X86::FP80_TO_INT32_IN_MEM:
19614   case X86::FP80_TO_INT64_IN_MEM: {
19615     MachineFunction *F = BB->getParent();
19616     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19617     DebugLoc DL = MI->getDebugLoc();
19618
19619     // Change the floating point control register to use "round towards zero"
19620     // mode when truncating to an integer value.
19621     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19622     addFrameReference(BuildMI(*BB, MI, DL,
19623                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19624
19625     // Load the old value of the high byte of the control word...
19626     unsigned OldCW =
19627       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19628     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19629                       CWFrameIdx);
19630
19631     // Set the high part to be round to zero...
19632     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19633       .addImm(0xC7F);
19634
19635     // Reload the modified control word now...
19636     addFrameReference(BuildMI(*BB, MI, DL,
19637                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19638
19639     // Restore the memory image of control word to original value
19640     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19641       .addReg(OldCW);
19642
19643     // Get the X86 opcode to use.
19644     unsigned Opc;
19645     switch (MI->getOpcode()) {
19646     default: llvm_unreachable("illegal opcode!");
19647     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19648     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19649     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19650     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19651     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19652     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19653     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19654     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19655     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19656     }
19657
19658     X86AddressMode AM;
19659     MachineOperand &Op = MI->getOperand(0);
19660     if (Op.isReg()) {
19661       AM.BaseType = X86AddressMode::RegBase;
19662       AM.Base.Reg = Op.getReg();
19663     } else {
19664       AM.BaseType = X86AddressMode::FrameIndexBase;
19665       AM.Base.FrameIndex = Op.getIndex();
19666     }
19667     Op = MI->getOperand(1);
19668     if (Op.isImm())
19669       AM.Scale = Op.getImm();
19670     Op = MI->getOperand(2);
19671     if (Op.isImm())
19672       AM.IndexReg = Op.getImm();
19673     Op = MI->getOperand(3);
19674     if (Op.isGlobal()) {
19675       AM.GV = Op.getGlobal();
19676     } else {
19677       AM.Disp = Op.getImm();
19678     }
19679     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19680                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19681
19682     // Reload the original control word now.
19683     addFrameReference(BuildMI(*BB, MI, DL,
19684                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19685
19686     MI->eraseFromParent();   // The pseudo instruction is gone now.
19687     return BB;
19688   }
19689     // String/text processing lowering.
19690   case X86::PCMPISTRM128REG:
19691   case X86::VPCMPISTRM128REG:
19692   case X86::PCMPISTRM128MEM:
19693   case X86::VPCMPISTRM128MEM:
19694   case X86::PCMPESTRM128REG:
19695   case X86::VPCMPESTRM128REG:
19696   case X86::PCMPESTRM128MEM:
19697   case X86::VPCMPESTRM128MEM:
19698     assert(Subtarget->hasSSE42() &&
19699            "Target must have SSE4.2 or AVX features enabled");
19700     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19701
19702   // String/text processing lowering.
19703   case X86::PCMPISTRIREG:
19704   case X86::VPCMPISTRIREG:
19705   case X86::PCMPISTRIMEM:
19706   case X86::VPCMPISTRIMEM:
19707   case X86::PCMPESTRIREG:
19708   case X86::VPCMPESTRIREG:
19709   case X86::PCMPESTRIMEM:
19710   case X86::VPCMPESTRIMEM:
19711     assert(Subtarget->hasSSE42() &&
19712            "Target must have SSE4.2 or AVX features enabled");
19713     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19714
19715   // Thread synchronization.
19716   case X86::MONITOR:
19717     return EmitMonitor(MI, BB, Subtarget);
19718
19719   // xbegin
19720   case X86::XBEGIN:
19721     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19722
19723   case X86::VASTART_SAVE_XMM_REGS:
19724     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19725
19726   case X86::VAARG_64:
19727     return EmitVAARG64WithCustomInserter(MI, BB);
19728
19729   case X86::EH_SjLj_SetJmp32:
19730   case X86::EH_SjLj_SetJmp64:
19731     return emitEHSjLjSetJmp(MI, BB);
19732
19733   case X86::EH_SjLj_LongJmp32:
19734   case X86::EH_SjLj_LongJmp64:
19735     return emitEHSjLjLongJmp(MI, BB);
19736
19737   case TargetOpcode::STATEPOINT:
19738     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19739     // this point in the process.  We diverge later.
19740     return emitPatchPoint(MI, BB);
19741
19742   case TargetOpcode::STACKMAP:
19743   case TargetOpcode::PATCHPOINT:
19744     return emitPatchPoint(MI, BB);
19745
19746   case X86::VFMADDPDr213r:
19747   case X86::VFMADDPSr213r:
19748   case X86::VFMADDSDr213r:
19749   case X86::VFMADDSSr213r:
19750   case X86::VFMSUBPDr213r:
19751   case X86::VFMSUBPSr213r:
19752   case X86::VFMSUBSDr213r:
19753   case X86::VFMSUBSSr213r:
19754   case X86::VFNMADDPDr213r:
19755   case X86::VFNMADDPSr213r:
19756   case X86::VFNMADDSDr213r:
19757   case X86::VFNMADDSSr213r:
19758   case X86::VFNMSUBPDr213r:
19759   case X86::VFNMSUBPSr213r:
19760   case X86::VFNMSUBSDr213r:
19761   case X86::VFNMSUBSSr213r:
19762   case X86::VFMADDSUBPDr213r:
19763   case X86::VFMADDSUBPSr213r:
19764   case X86::VFMSUBADDPDr213r:
19765   case X86::VFMSUBADDPSr213r:
19766   case X86::VFMADDPDr213rY:
19767   case X86::VFMADDPSr213rY:
19768   case X86::VFMSUBPDr213rY:
19769   case X86::VFMSUBPSr213rY:
19770   case X86::VFNMADDPDr213rY:
19771   case X86::VFNMADDPSr213rY:
19772   case X86::VFNMSUBPDr213rY:
19773   case X86::VFNMSUBPSr213rY:
19774   case X86::VFMADDSUBPDr213rY:
19775   case X86::VFMADDSUBPSr213rY:
19776   case X86::VFMSUBADDPDr213rY:
19777   case X86::VFMSUBADDPSr213rY:
19778     return emitFMA3Instr(MI, BB);
19779   }
19780 }
19781
19782 //===----------------------------------------------------------------------===//
19783 //                           X86 Optimization Hooks
19784 //===----------------------------------------------------------------------===//
19785
19786 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19787                                                       APInt &KnownZero,
19788                                                       APInt &KnownOne,
19789                                                       const SelectionDAG &DAG,
19790                                                       unsigned Depth) const {
19791   unsigned BitWidth = KnownZero.getBitWidth();
19792   unsigned Opc = Op.getOpcode();
19793   assert((Opc >= ISD::BUILTIN_OP_END ||
19794           Opc == ISD::INTRINSIC_WO_CHAIN ||
19795           Opc == ISD::INTRINSIC_W_CHAIN ||
19796           Opc == ISD::INTRINSIC_VOID) &&
19797          "Should use MaskedValueIsZero if you don't know whether Op"
19798          " is a target node!");
19799
19800   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19801   switch (Opc) {
19802   default: break;
19803   case X86ISD::ADD:
19804   case X86ISD::SUB:
19805   case X86ISD::ADC:
19806   case X86ISD::SBB:
19807   case X86ISD::SMUL:
19808   case X86ISD::UMUL:
19809   case X86ISD::INC:
19810   case X86ISD::DEC:
19811   case X86ISD::OR:
19812   case X86ISD::XOR:
19813   case X86ISD::AND:
19814     // These nodes' second result is a boolean.
19815     if (Op.getResNo() == 0)
19816       break;
19817     // Fallthrough
19818   case X86ISD::SETCC:
19819     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19820     break;
19821   case ISD::INTRINSIC_WO_CHAIN: {
19822     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19823     unsigned NumLoBits = 0;
19824     switch (IntId) {
19825     default: break;
19826     case Intrinsic::x86_sse_movmsk_ps:
19827     case Intrinsic::x86_avx_movmsk_ps_256:
19828     case Intrinsic::x86_sse2_movmsk_pd:
19829     case Intrinsic::x86_avx_movmsk_pd_256:
19830     case Intrinsic::x86_mmx_pmovmskb:
19831     case Intrinsic::x86_sse2_pmovmskb_128:
19832     case Intrinsic::x86_avx2_pmovmskb: {
19833       // High bits of movmskp{s|d}, pmovmskb are known zero.
19834       switch (IntId) {
19835         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19836         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19837         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19838         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19839         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19840         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19841         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19842         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19843       }
19844       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19845       break;
19846     }
19847     }
19848     break;
19849   }
19850   }
19851 }
19852
19853 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19854   SDValue Op,
19855   const SelectionDAG &,
19856   unsigned Depth) const {
19857   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19858   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19859     return Op.getValueType().getScalarType().getSizeInBits();
19860
19861   // Fallback case.
19862   return 1;
19863 }
19864
19865 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19866 /// node is a GlobalAddress + offset.
19867 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19868                                        const GlobalValue* &GA,
19869                                        int64_t &Offset) const {
19870   if (N->getOpcode() == X86ISD::Wrapper) {
19871     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19872       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19873       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19874       return true;
19875     }
19876   }
19877   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19878 }
19879
19880 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19881 /// same as extracting the high 128-bit part of 256-bit vector and then
19882 /// inserting the result into the low part of a new 256-bit vector
19883 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19884   EVT VT = SVOp->getValueType(0);
19885   unsigned NumElems = VT.getVectorNumElements();
19886
19887   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19888   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19889     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19890         SVOp->getMaskElt(j) >= 0)
19891       return false;
19892
19893   return true;
19894 }
19895
19896 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19897 /// same as extracting the low 128-bit part of 256-bit vector and then
19898 /// inserting the result into the high part of a new 256-bit vector
19899 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19900   EVT VT = SVOp->getValueType(0);
19901   unsigned NumElems = VT.getVectorNumElements();
19902
19903   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19904   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19905     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19906         SVOp->getMaskElt(j) >= 0)
19907       return false;
19908
19909   return true;
19910 }
19911
19912 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19913 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19914                                         TargetLowering::DAGCombinerInfo &DCI,
19915                                         const X86Subtarget* Subtarget) {
19916   SDLoc dl(N);
19917   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19918   SDValue V1 = SVOp->getOperand(0);
19919   SDValue V2 = SVOp->getOperand(1);
19920   EVT VT = SVOp->getValueType(0);
19921   unsigned NumElems = VT.getVectorNumElements();
19922
19923   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19924       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19925     //
19926     //                   0,0,0,...
19927     //                      |
19928     //    V      UNDEF    BUILD_VECTOR    UNDEF
19929     //     \      /           \           /
19930     //  CONCAT_VECTOR         CONCAT_VECTOR
19931     //         \                  /
19932     //          \                /
19933     //          RESULT: V + zero extended
19934     //
19935     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19936         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19937         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19938       return SDValue();
19939
19940     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19941       return SDValue();
19942
19943     // To match the shuffle mask, the first half of the mask should
19944     // be exactly the first vector, and all the rest a splat with the
19945     // first element of the second one.
19946     for (unsigned i = 0; i != NumElems/2; ++i)
19947       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19948           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19949         return SDValue();
19950
19951     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19952     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19953       if (Ld->hasNUsesOfValue(1, 0)) {
19954         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19955         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19956         SDValue ResNode =
19957           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19958                                   Ld->getMemoryVT(),
19959                                   Ld->getPointerInfo(),
19960                                   Ld->getAlignment(),
19961                                   false/*isVolatile*/, true/*ReadMem*/,
19962                                   false/*WriteMem*/);
19963
19964         // Make sure the newly-created LOAD is in the same position as Ld in
19965         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19966         // and update uses of Ld's output chain to use the TokenFactor.
19967         if (Ld->hasAnyUseOfValue(1)) {
19968           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19969                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19970           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19971           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19972                                  SDValue(ResNode.getNode(), 1));
19973         }
19974
19975         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19976       }
19977     }
19978
19979     // Emit a zeroed vector and insert the desired subvector on its
19980     // first half.
19981     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19982     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19983     return DCI.CombineTo(N, InsV);
19984   }
19985
19986   //===--------------------------------------------------------------------===//
19987   // Combine some shuffles into subvector extracts and inserts:
19988   //
19989
19990   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19991   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19992     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19993     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19994     return DCI.CombineTo(N, InsV);
19995   }
19996
19997   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19998   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19999     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20000     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20001     return DCI.CombineTo(N, InsV);
20002   }
20003
20004   return SDValue();
20005 }
20006
20007 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20008 /// possible.
20009 ///
20010 /// This is the leaf of the recursive combinine below. When we have found some
20011 /// chain of single-use x86 shuffle instructions and accumulated the combined
20012 /// shuffle mask represented by them, this will try to pattern match that mask
20013 /// into either a single instruction if there is a special purpose instruction
20014 /// for this operation, or into a PSHUFB instruction which is a fully general
20015 /// instruction but should only be used to replace chains over a certain depth.
20016 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20017                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20018                                    TargetLowering::DAGCombinerInfo &DCI,
20019                                    const X86Subtarget *Subtarget) {
20020   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20021
20022   // Find the operand that enters the chain. Note that multiple uses are OK
20023   // here, we're not going to remove the operand we find.
20024   SDValue Input = Op.getOperand(0);
20025   while (Input.getOpcode() == ISD::BITCAST)
20026     Input = Input.getOperand(0);
20027
20028   MVT VT = Input.getSimpleValueType();
20029   MVT RootVT = Root.getSimpleValueType();
20030   SDLoc DL(Root);
20031
20032   // Just remove no-op shuffle masks.
20033   if (Mask.size() == 1) {
20034     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
20035                   /*AddTo*/ true);
20036     return true;
20037   }
20038
20039   // Use the float domain if the operand type is a floating point type.
20040   bool FloatDomain = VT.isFloatingPoint();
20041
20042   // For floating point shuffles, we don't have free copies in the shuffle
20043   // instructions or the ability to load as part of the instruction, so
20044   // canonicalize their shuffles to UNPCK or MOV variants.
20045   //
20046   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20047   // vectors because it can have a load folded into it that UNPCK cannot. This
20048   // doesn't preclude something switching to the shorter encoding post-RA.
20049   //
20050   // FIXME: Should teach these routines about AVX vector widths.
20051   if (FloatDomain && VT.getSizeInBits() == 128) {
20052     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20053       bool Lo = Mask.equals({0, 0});
20054       unsigned Shuffle;
20055       MVT ShuffleVT;
20056       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20057       // is no slower than UNPCKLPD but has the option to fold the input operand
20058       // into even an unaligned memory load.
20059       if (Lo && Subtarget->hasSSE3()) {
20060         Shuffle = X86ISD::MOVDDUP;
20061         ShuffleVT = MVT::v2f64;
20062       } else {
20063         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20064         // than the UNPCK variants.
20065         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20066         ShuffleVT = MVT::v4f32;
20067       }
20068       if (Depth == 1 && Root->getOpcode() == Shuffle)
20069         return false; // Nothing to do!
20070       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20071       DCI.AddToWorklist(Op.getNode());
20072       if (Shuffle == X86ISD::MOVDDUP)
20073         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20074       else
20075         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
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     if (Subtarget->hasSSE3() &&
20082         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20083       bool Lo = Mask.equals({0, 0, 2, 2});
20084       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20085       MVT ShuffleVT = MVT::v4f32;
20086       if (Depth == 1 && Root->getOpcode() == Shuffle)
20087         return false; // Nothing to do!
20088       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20089       DCI.AddToWorklist(Op.getNode());
20090       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20091       DCI.AddToWorklist(Op.getNode());
20092       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20093                     /*AddTo*/ true);
20094       return true;
20095     }
20096     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20097       bool Lo = Mask.equals({0, 0, 1, 1});
20098       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20099       MVT ShuffleVT = MVT::v4f32;
20100       if (Depth == 1 && Root->getOpcode() == Shuffle)
20101         return false; // Nothing to do!
20102       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20103       DCI.AddToWorklist(Op.getNode());
20104       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20105       DCI.AddToWorklist(Op.getNode());
20106       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20107                     /*AddTo*/ true);
20108       return true;
20109     }
20110   }
20111
20112   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20113   // variants as none of these have single-instruction variants that are
20114   // superior to the UNPCK formulation.
20115   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20116       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20117        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20118        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20119        Mask.equals(
20120            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20121     bool Lo = Mask[0] == 0;
20122     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20123     if (Depth == 1 && Root->getOpcode() == Shuffle)
20124       return false; // Nothing to do!
20125     MVT ShuffleVT;
20126     switch (Mask.size()) {
20127     case 8:
20128       ShuffleVT = MVT::v8i16;
20129       break;
20130     case 16:
20131       ShuffleVT = MVT::v16i8;
20132       break;
20133     default:
20134       llvm_unreachable("Impossible mask size!");
20135     };
20136     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20137     DCI.AddToWorklist(Op.getNode());
20138     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20139     DCI.AddToWorklist(Op.getNode());
20140     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20141                   /*AddTo*/ true);
20142     return true;
20143   }
20144
20145   // Don't try to re-form single instruction chains under any circumstances now
20146   // that we've done encoding canonicalization for them.
20147   if (Depth < 2)
20148     return false;
20149
20150   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20151   // can replace them with a single PSHUFB instruction profitably. Intel's
20152   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20153   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20154   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20155     SmallVector<SDValue, 16> PSHUFBMask;
20156     int NumBytes = VT.getSizeInBits() / 8;
20157     int Ratio = NumBytes / Mask.size();
20158     for (int i = 0; i < NumBytes; ++i) {
20159       if (Mask[i / Ratio] == SM_SentinelUndef) {
20160         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20161         continue;
20162       }
20163       int M = Mask[i / Ratio] != SM_SentinelZero
20164                   ? Ratio * Mask[i / Ratio] + i % Ratio
20165                   : 255;
20166       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20167     }
20168     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20169     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20170     DCI.AddToWorklist(Op.getNode());
20171     SDValue PSHUFBMaskOp =
20172         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20173     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20174     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20175     DCI.AddToWorklist(Op.getNode());
20176     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20177                   /*AddTo*/ true);
20178     return true;
20179   }
20180
20181   // Failed to find any combines.
20182   return false;
20183 }
20184
20185 /// \brief Fully generic combining of x86 shuffle instructions.
20186 ///
20187 /// This should be the last combine run over the x86 shuffle instructions. Once
20188 /// they have been fully optimized, this will recursively consider all chains
20189 /// of single-use shuffle instructions, build a generic model of the cumulative
20190 /// shuffle operation, and check for simpler instructions which implement this
20191 /// operation. We use this primarily for two purposes:
20192 ///
20193 /// 1) Collapse generic shuffles to specialized single instructions when
20194 ///    equivalent. In most cases, this is just an encoding size win, but
20195 ///    sometimes we will collapse multiple generic shuffles into a single
20196 ///    special-purpose shuffle.
20197 /// 2) Look for sequences of shuffle instructions with 3 or more total
20198 ///    instructions, and replace them with the slightly more expensive SSSE3
20199 ///    PSHUFB instruction if available. We do this as the last combining step
20200 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20201 ///    a suitable short sequence of other instructions. The PHUFB will either
20202 ///    use a register or have to read from memory and so is slightly (but only
20203 ///    slightly) more expensive than the other shuffle instructions.
20204 ///
20205 /// Because this is inherently a quadratic operation (for each shuffle in
20206 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20207 /// This should never be an issue in practice as the shuffle lowering doesn't
20208 /// produce sequences of more than 8 instructions.
20209 ///
20210 /// FIXME: We will currently miss some cases where the redundant shuffling
20211 /// would simplify under the threshold for PSHUFB formation because of
20212 /// combine-ordering. To fix this, we should do the redundant instruction
20213 /// combining in this recursive walk.
20214 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20215                                           ArrayRef<int> RootMask,
20216                                           int Depth, bool HasPSHUFB,
20217                                           SelectionDAG &DAG,
20218                                           TargetLowering::DAGCombinerInfo &DCI,
20219                                           const X86Subtarget *Subtarget) {
20220   // Bound the depth of our recursive combine because this is ultimately
20221   // quadratic in nature.
20222   if (Depth > 8)
20223     return false;
20224
20225   // Directly rip through bitcasts to find the underlying operand.
20226   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20227     Op = Op.getOperand(0);
20228
20229   MVT VT = Op.getSimpleValueType();
20230   if (!VT.isVector())
20231     return false; // Bail if we hit a non-vector.
20232
20233   assert(Root.getSimpleValueType().isVector() &&
20234          "Shuffles operate on vector types!");
20235   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20236          "Can only combine shuffles of the same vector register size.");
20237
20238   if (!isTargetShuffle(Op.getOpcode()))
20239     return false;
20240   SmallVector<int, 16> OpMask;
20241   bool IsUnary;
20242   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20243   // We only can combine unary shuffles which we can decode the mask for.
20244   if (!HaveMask || !IsUnary)
20245     return false;
20246
20247   assert(VT.getVectorNumElements() == OpMask.size() &&
20248          "Different mask size from vector size!");
20249   assert(((RootMask.size() > OpMask.size() &&
20250            RootMask.size() % OpMask.size() == 0) ||
20251           (OpMask.size() > RootMask.size() &&
20252            OpMask.size() % RootMask.size() == 0) ||
20253           OpMask.size() == RootMask.size()) &&
20254          "The smaller number of elements must divide the larger.");
20255   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20256   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20257   assert(((RootRatio == 1 && OpRatio == 1) ||
20258           (RootRatio == 1) != (OpRatio == 1)) &&
20259          "Must not have a ratio for both incoming and op masks!");
20260
20261   SmallVector<int, 16> Mask;
20262   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20263
20264   // Merge this shuffle operation's mask into our accumulated mask. Note that
20265   // this shuffle's mask will be the first applied to the input, followed by the
20266   // root mask to get us all the way to the root value arrangement. The reason
20267   // for this order is that we are recursing up the operation chain.
20268   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20269     int RootIdx = i / RootRatio;
20270     if (RootMask[RootIdx] < 0) {
20271       // This is a zero or undef lane, we're done.
20272       Mask.push_back(RootMask[RootIdx]);
20273       continue;
20274     }
20275
20276     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20277     int OpIdx = RootMaskedIdx / OpRatio;
20278     if (OpMask[OpIdx] < 0) {
20279       // The incoming lanes are zero or undef, it doesn't matter which ones we
20280       // are using.
20281       Mask.push_back(OpMask[OpIdx]);
20282       continue;
20283     }
20284
20285     // Ok, we have non-zero lanes, map them through.
20286     Mask.push_back(OpMask[OpIdx] * OpRatio +
20287                    RootMaskedIdx % OpRatio);
20288   }
20289
20290   // See if we can recurse into the operand to combine more things.
20291   switch (Op.getOpcode()) {
20292     case X86ISD::PSHUFB:
20293       HasPSHUFB = true;
20294     case X86ISD::PSHUFD:
20295     case X86ISD::PSHUFHW:
20296     case X86ISD::PSHUFLW:
20297       if (Op.getOperand(0).hasOneUse() &&
20298           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20299                                         HasPSHUFB, DAG, DCI, Subtarget))
20300         return true;
20301       break;
20302
20303     case X86ISD::UNPCKL:
20304     case X86ISD::UNPCKH:
20305       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20306       // We can't check for single use, we have to check that this shuffle is the only user.
20307       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20308           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20309                                         HasPSHUFB, DAG, DCI, Subtarget))
20310           return true;
20311       break;
20312   }
20313
20314   // Minor canonicalization of the accumulated shuffle mask to make it easier
20315   // to match below. All this does is detect masks with squential pairs of
20316   // elements, and shrink them to the half-width mask. It does this in a loop
20317   // so it will reduce the size of the mask to the minimal width mask which
20318   // performs an equivalent shuffle.
20319   SmallVector<int, 16> WidenedMask;
20320   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20321     Mask = std::move(WidenedMask);
20322     WidenedMask.clear();
20323   }
20324
20325   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20326                                 Subtarget);
20327 }
20328
20329 /// \brief Get the PSHUF-style mask from PSHUF node.
20330 ///
20331 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20332 /// PSHUF-style masks that can be reused with such instructions.
20333 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20334   MVT VT = N.getSimpleValueType();
20335   SmallVector<int, 4> Mask;
20336   bool IsUnary;
20337   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20338   (void)HaveMask;
20339   assert(HaveMask);
20340
20341   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20342   // matter. Check that the upper masks are repeats and remove them.
20343   if (VT.getSizeInBits() > 128) {
20344     int LaneElts = 128 / VT.getScalarSizeInBits();
20345 #ifndef NDEBUG
20346     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20347       for (int j = 0; j < LaneElts; ++j)
20348         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20349                "Mask doesn't repeat in high 128-bit lanes!");
20350 #endif
20351     Mask.resize(LaneElts);
20352   }
20353
20354   switch (N.getOpcode()) {
20355   case X86ISD::PSHUFD:
20356     return Mask;
20357   case X86ISD::PSHUFLW:
20358     Mask.resize(4);
20359     return Mask;
20360   case X86ISD::PSHUFHW:
20361     Mask.erase(Mask.begin(), Mask.begin() + 4);
20362     for (int &M : Mask)
20363       M -= 4;
20364     return Mask;
20365   default:
20366     llvm_unreachable("No valid shuffle instruction found!");
20367   }
20368 }
20369
20370 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20371 ///
20372 /// We walk up the chain and look for a combinable shuffle, skipping over
20373 /// shuffles that we could hoist this shuffle's transformation past without
20374 /// altering anything.
20375 static SDValue
20376 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20377                              SelectionDAG &DAG,
20378                              TargetLowering::DAGCombinerInfo &DCI) {
20379   assert(N.getOpcode() == X86ISD::PSHUFD &&
20380          "Called with something other than an x86 128-bit half shuffle!");
20381   SDLoc DL(N);
20382
20383   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20384   // of the shuffles in the chain so that we can form a fresh chain to replace
20385   // this one.
20386   SmallVector<SDValue, 8> Chain;
20387   SDValue V = N.getOperand(0);
20388   for (; V.hasOneUse(); V = V.getOperand(0)) {
20389     switch (V.getOpcode()) {
20390     default:
20391       return SDValue(); // Nothing combined!
20392
20393     case ISD::BITCAST:
20394       // Skip bitcasts as we always know the type for the target specific
20395       // instructions.
20396       continue;
20397
20398     case X86ISD::PSHUFD:
20399       // Found another dword shuffle.
20400       break;
20401
20402     case X86ISD::PSHUFLW:
20403       // Check that the low words (being shuffled) are the identity in the
20404       // dword shuffle, and the high words are self-contained.
20405       if (Mask[0] != 0 || Mask[1] != 1 ||
20406           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20407         return SDValue();
20408
20409       Chain.push_back(V);
20410       continue;
20411
20412     case X86ISD::PSHUFHW:
20413       // Check that the high words (being shuffled) are the identity in the
20414       // dword shuffle, and the low words are self-contained.
20415       if (Mask[2] != 2 || Mask[3] != 3 ||
20416           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20417         return SDValue();
20418
20419       Chain.push_back(V);
20420       continue;
20421
20422     case X86ISD::UNPCKL:
20423     case X86ISD::UNPCKH:
20424       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20425       // shuffle into a preceding word shuffle.
20426       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20427           V.getSimpleValueType().getScalarType() != MVT::i16)
20428         return SDValue();
20429
20430       // Search for a half-shuffle which we can combine with.
20431       unsigned CombineOp =
20432           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20433       if (V.getOperand(0) != V.getOperand(1) ||
20434           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20435         return SDValue();
20436       Chain.push_back(V);
20437       V = V.getOperand(0);
20438       do {
20439         switch (V.getOpcode()) {
20440         default:
20441           return SDValue(); // Nothing to combine.
20442
20443         case X86ISD::PSHUFLW:
20444         case X86ISD::PSHUFHW:
20445           if (V.getOpcode() == CombineOp)
20446             break;
20447
20448           Chain.push_back(V);
20449
20450           // Fallthrough!
20451         case ISD::BITCAST:
20452           V = V.getOperand(0);
20453           continue;
20454         }
20455         break;
20456       } while (V.hasOneUse());
20457       break;
20458     }
20459     // Break out of the loop if we break out of the switch.
20460     break;
20461   }
20462
20463   if (!V.hasOneUse())
20464     // We fell out of the loop without finding a viable combining instruction.
20465     return SDValue();
20466
20467   // Merge this node's mask and our incoming mask.
20468   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20469   for (int &M : Mask)
20470     M = VMask[M];
20471   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20472                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20473
20474   // Rebuild the chain around this new shuffle.
20475   while (!Chain.empty()) {
20476     SDValue W = Chain.pop_back_val();
20477
20478     if (V.getValueType() != W.getOperand(0).getValueType())
20479       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20480
20481     switch (W.getOpcode()) {
20482     default:
20483       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20484
20485     case X86ISD::UNPCKL:
20486     case X86ISD::UNPCKH:
20487       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20488       break;
20489
20490     case X86ISD::PSHUFD:
20491     case X86ISD::PSHUFLW:
20492     case X86ISD::PSHUFHW:
20493       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20494       break;
20495     }
20496   }
20497   if (V.getValueType() != N.getValueType())
20498     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20499
20500   // Return the new chain to replace N.
20501   return V;
20502 }
20503
20504 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20505 ///
20506 /// We walk up the chain, skipping shuffles of the other half and looking
20507 /// through shuffles which switch halves trying to find a shuffle of the same
20508 /// pair of dwords.
20509 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20510                                         SelectionDAG &DAG,
20511                                         TargetLowering::DAGCombinerInfo &DCI) {
20512   assert(
20513       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20514       "Called with something other than an x86 128-bit half shuffle!");
20515   SDLoc DL(N);
20516   unsigned CombineOpcode = N.getOpcode();
20517
20518   // Walk up a single-use chain looking for a combinable shuffle.
20519   SDValue V = N.getOperand(0);
20520   for (; V.hasOneUse(); V = V.getOperand(0)) {
20521     switch (V.getOpcode()) {
20522     default:
20523       return false; // Nothing combined!
20524
20525     case ISD::BITCAST:
20526       // Skip bitcasts as we always know the type for the target specific
20527       // instructions.
20528       continue;
20529
20530     case X86ISD::PSHUFLW:
20531     case X86ISD::PSHUFHW:
20532       if (V.getOpcode() == CombineOpcode)
20533         break;
20534
20535       // Other-half shuffles are no-ops.
20536       continue;
20537     }
20538     // Break out of the loop if we break out of the switch.
20539     break;
20540   }
20541
20542   if (!V.hasOneUse())
20543     // We fell out of the loop without finding a viable combining instruction.
20544     return false;
20545
20546   // Combine away the bottom node as its shuffle will be accumulated into
20547   // a preceding shuffle.
20548   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20549
20550   // Record the old value.
20551   SDValue Old = V;
20552
20553   // Merge this node's mask and our incoming mask (adjusted to account for all
20554   // the pshufd instructions encountered).
20555   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20556   for (int &M : Mask)
20557     M = VMask[M];
20558   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20559                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20560
20561   // Check that the shuffles didn't cancel each other out. If not, we need to
20562   // combine to the new one.
20563   if (Old != V)
20564     // Replace the combinable shuffle with the combined one, updating all users
20565     // so that we re-evaluate the chain here.
20566     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20567
20568   return true;
20569 }
20570
20571 /// \brief Try to combine x86 target specific shuffles.
20572 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20573                                            TargetLowering::DAGCombinerInfo &DCI,
20574                                            const X86Subtarget *Subtarget) {
20575   SDLoc DL(N);
20576   MVT VT = N.getSimpleValueType();
20577   SmallVector<int, 4> Mask;
20578
20579   switch (N.getOpcode()) {
20580   case X86ISD::PSHUFD:
20581   case X86ISD::PSHUFLW:
20582   case X86ISD::PSHUFHW:
20583     Mask = getPSHUFShuffleMask(N);
20584     assert(Mask.size() == 4);
20585     break;
20586   default:
20587     return SDValue();
20588   }
20589
20590   // Nuke no-op shuffles that show up after combining.
20591   if (isNoopShuffleMask(Mask))
20592     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20593
20594   // Look for simplifications involving one or two shuffle instructions.
20595   SDValue V = N.getOperand(0);
20596   switch (N.getOpcode()) {
20597   default:
20598     break;
20599   case X86ISD::PSHUFLW:
20600   case X86ISD::PSHUFHW:
20601     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20602
20603     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20604       return SDValue(); // We combined away this shuffle, so we're done.
20605
20606     // See if this reduces to a PSHUFD which is no more expensive and can
20607     // combine with more operations. Note that it has to at least flip the
20608     // dwords as otherwise it would have been removed as a no-op.
20609     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20610       int DMask[] = {0, 1, 2, 3};
20611       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20612       DMask[DOffset + 0] = DOffset + 1;
20613       DMask[DOffset + 1] = DOffset + 0;
20614       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20615       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20616       DCI.AddToWorklist(V.getNode());
20617       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20618                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20619       DCI.AddToWorklist(V.getNode());
20620       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20621     }
20622
20623     // Look for shuffle patterns which can be implemented as a single unpack.
20624     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20625     // only works when we have a PSHUFD followed by two half-shuffles.
20626     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20627         (V.getOpcode() == X86ISD::PSHUFLW ||
20628          V.getOpcode() == X86ISD::PSHUFHW) &&
20629         V.getOpcode() != N.getOpcode() &&
20630         V.hasOneUse()) {
20631       SDValue D = V.getOperand(0);
20632       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20633         D = D.getOperand(0);
20634       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20635         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20636         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20637         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20638         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20639         int WordMask[8];
20640         for (int i = 0; i < 4; ++i) {
20641           WordMask[i + NOffset] = Mask[i] + NOffset;
20642           WordMask[i + VOffset] = VMask[i] + VOffset;
20643         }
20644         // Map the word mask through the DWord mask.
20645         int MappedMask[8];
20646         for (int i = 0; i < 8; ++i)
20647           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20648         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20649             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20650           // We can replace all three shuffles with an unpack.
20651           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20652           DCI.AddToWorklist(V.getNode());
20653           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20654                                                 : X86ISD::UNPCKH,
20655                              DL, VT, V, V);
20656         }
20657       }
20658     }
20659
20660     break;
20661
20662   case X86ISD::PSHUFD:
20663     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20664       return NewN;
20665
20666     break;
20667   }
20668
20669   return SDValue();
20670 }
20671
20672 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20673 ///
20674 /// We combine this directly on the abstract vector shuffle nodes so it is
20675 /// easier to generically match. We also insert dummy vector shuffle nodes for
20676 /// the operands which explicitly discard the lanes which are unused by this
20677 /// operation to try to flow through the rest of the combiner the fact that
20678 /// they're unused.
20679 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20680   SDLoc DL(N);
20681   EVT VT = N->getValueType(0);
20682
20683   // We only handle target-independent shuffles.
20684   // FIXME: It would be easy and harmless to use the target shuffle mask
20685   // extraction tool to support more.
20686   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20687     return SDValue();
20688
20689   auto *SVN = cast<ShuffleVectorSDNode>(N);
20690   ArrayRef<int> Mask = SVN->getMask();
20691   SDValue V1 = N->getOperand(0);
20692   SDValue V2 = N->getOperand(1);
20693
20694   // We require the first shuffle operand to be the SUB node, and the second to
20695   // be the ADD node.
20696   // FIXME: We should support the commuted patterns.
20697   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20698     return SDValue();
20699
20700   // If there are other uses of these operations we can't fold them.
20701   if (!V1->hasOneUse() || !V2->hasOneUse())
20702     return SDValue();
20703
20704   // Ensure that both operations have the same operands. Note that we can
20705   // commute the FADD operands.
20706   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20707   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20708       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20709     return SDValue();
20710
20711   // We're looking for blends between FADD and FSUB nodes. We insist on these
20712   // nodes being lined up in a specific expected pattern.
20713   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20714         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20715         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20716     return SDValue();
20717
20718   // Only specific types are legal at this point, assert so we notice if and
20719   // when these change.
20720   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20721           VT == MVT::v4f64) &&
20722          "Unknown vector type encountered!");
20723
20724   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20725 }
20726
20727 /// PerformShuffleCombine - Performs several different shuffle combines.
20728 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20729                                      TargetLowering::DAGCombinerInfo &DCI,
20730                                      const X86Subtarget *Subtarget) {
20731   SDLoc dl(N);
20732   SDValue N0 = N->getOperand(0);
20733   SDValue N1 = N->getOperand(1);
20734   EVT VT = N->getValueType(0);
20735
20736   // Don't create instructions with illegal types after legalize types has run.
20737   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20738   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20739     return SDValue();
20740
20741   // If we have legalized the vector types, look for blends of FADD and FSUB
20742   // nodes that we can fuse into an ADDSUB node.
20743   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20744     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20745       return AddSub;
20746
20747   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20748   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20749       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20750     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20751
20752   // During Type Legalization, when promoting illegal vector types,
20753   // the backend might introduce new shuffle dag nodes and bitcasts.
20754   //
20755   // This code performs the following transformation:
20756   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20757   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20758   //
20759   // We do this only if both the bitcast and the BINOP dag nodes have
20760   // one use. Also, perform this transformation only if the new binary
20761   // operation is legal. This is to avoid introducing dag nodes that
20762   // potentially need to be further expanded (or custom lowered) into a
20763   // less optimal sequence of dag nodes.
20764   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20765       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20766       N0.getOpcode() == ISD::BITCAST) {
20767     SDValue BC0 = N0.getOperand(0);
20768     EVT SVT = BC0.getValueType();
20769     unsigned Opcode = BC0.getOpcode();
20770     unsigned NumElts = VT.getVectorNumElements();
20771
20772     if (BC0.hasOneUse() && SVT.isVector() &&
20773         SVT.getVectorNumElements() * 2 == NumElts &&
20774         TLI.isOperationLegal(Opcode, VT)) {
20775       bool CanFold = false;
20776       switch (Opcode) {
20777       default : break;
20778       case ISD::ADD :
20779       case ISD::FADD :
20780       case ISD::SUB :
20781       case ISD::FSUB :
20782       case ISD::MUL :
20783       case ISD::FMUL :
20784         CanFold = true;
20785       }
20786
20787       unsigned SVTNumElts = SVT.getVectorNumElements();
20788       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20789       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20790         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20791       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20792         CanFold = SVOp->getMaskElt(i) < 0;
20793
20794       if (CanFold) {
20795         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20796         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20797         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20798         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20799       }
20800     }
20801   }
20802
20803   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20804   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20805   // consecutive, non-overlapping, and in the right order.
20806   SmallVector<SDValue, 16> Elts;
20807   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20808     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20809
20810   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20811   if (LD.getNode())
20812     return LD;
20813
20814   if (isTargetShuffle(N->getOpcode())) {
20815     SDValue Shuffle =
20816         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20817     if (Shuffle.getNode())
20818       return Shuffle;
20819
20820     // Try recursively combining arbitrary sequences of x86 shuffle
20821     // instructions into higher-order shuffles. We do this after combining
20822     // specific PSHUF instruction sequences into their minimal form so that we
20823     // can evaluate how many specialized shuffle instructions are involved in
20824     // a particular chain.
20825     SmallVector<int, 1> NonceMask; // Just a placeholder.
20826     NonceMask.push_back(0);
20827     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20828                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20829                                       DCI, Subtarget))
20830       return SDValue(); // This routine will use CombineTo to replace N.
20831   }
20832
20833   return SDValue();
20834 }
20835
20836 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20837 /// specific shuffle of a load can be folded into a single element load.
20838 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20839 /// shuffles have been custom lowered so we need to handle those here.
20840 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20841                                          TargetLowering::DAGCombinerInfo &DCI) {
20842   if (DCI.isBeforeLegalizeOps())
20843     return SDValue();
20844
20845   SDValue InVec = N->getOperand(0);
20846   SDValue EltNo = N->getOperand(1);
20847
20848   if (!isa<ConstantSDNode>(EltNo))
20849     return SDValue();
20850
20851   EVT OriginalVT = InVec.getValueType();
20852
20853   if (InVec.getOpcode() == ISD::BITCAST) {
20854     // Don't duplicate a load with other uses.
20855     if (!InVec.hasOneUse())
20856       return SDValue();
20857     EVT BCVT = InVec.getOperand(0).getValueType();
20858     if (!BCVT.isVector() || 
20859         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20860       return SDValue();
20861     InVec = InVec.getOperand(0);
20862   }
20863
20864   EVT CurrentVT = InVec.getValueType();
20865
20866   if (!isTargetShuffle(InVec.getOpcode()))
20867     return SDValue();
20868
20869   // Don't duplicate a load with other uses.
20870   if (!InVec.hasOneUse())
20871     return SDValue();
20872
20873   SmallVector<int, 16> ShuffleMask;
20874   bool UnaryShuffle;
20875   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20876                             ShuffleMask, UnaryShuffle))
20877     return SDValue();
20878
20879   // Select the input vector, guarding against out of range extract vector.
20880   unsigned NumElems = CurrentVT.getVectorNumElements();
20881   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20882   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20883   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20884                                          : InVec.getOperand(1);
20885
20886   // If inputs to shuffle are the same for both ops, then allow 2 uses
20887   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20888                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20889
20890   if (LdNode.getOpcode() == ISD::BITCAST) {
20891     // Don't duplicate a load with other uses.
20892     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20893       return SDValue();
20894
20895     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20896     LdNode = LdNode.getOperand(0);
20897   }
20898
20899   if (!ISD::isNormalLoad(LdNode.getNode()))
20900     return SDValue();
20901
20902   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20903
20904   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20905     return SDValue();
20906
20907   EVT EltVT = N->getValueType(0);
20908   // If there's a bitcast before the shuffle, check if the load type and
20909   // alignment is valid.
20910   unsigned Align = LN0->getAlignment();
20911   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20912   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20913       EltVT.getTypeForEVT(*DAG.getContext()));
20914
20915   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20916     return SDValue();
20917
20918   // All checks match so transform back to vector_shuffle so that DAG combiner
20919   // can finish the job
20920   SDLoc dl(N);
20921
20922   // Create shuffle node taking into account the case that its a unary shuffle
20923   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20924                                    : InVec.getOperand(1);
20925   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20926                                  InVec.getOperand(0), Shuffle,
20927                                  &ShuffleMask[0]);
20928   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20929   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20930                      EltNo);
20931 }
20932
20933 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20934 /// special and don't usually play with other vector types, it's better to
20935 /// handle them early to be sure we emit efficient code by avoiding
20936 /// store-load conversions.
20937 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20938   if (N->getValueType(0) != MVT::x86mmx ||
20939       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20940       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20941     return SDValue();
20942
20943   SDValue V = N->getOperand(0);
20944   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20945   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20946     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20947                        N->getValueType(0), V.getOperand(0));
20948
20949   return SDValue();
20950 }
20951
20952 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20953 /// generation and convert it from being a bunch of shuffles and extracts
20954 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20955 /// storing the value and loading scalars back, while for x64 we should
20956 /// use 64-bit extracts and shifts.
20957 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20958                                          TargetLowering::DAGCombinerInfo &DCI) {
20959   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20960   if (NewOp.getNode())
20961     return NewOp;
20962
20963   SDValue InputVector = N->getOperand(0);
20964   SDLoc dl(InputVector);
20965   // Detect mmx to i32 conversion through a v2i32 elt extract.
20966   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20967       N->getValueType(0) == MVT::i32 &&
20968       InputVector.getValueType() == MVT::v2i32) {
20969
20970     // The bitcast source is a direct mmx result.
20971     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20972     if (MMXSrc.getValueType() == MVT::x86mmx)
20973       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20974                          N->getValueType(0),
20975                          InputVector.getNode()->getOperand(0));
20976
20977     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20978     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20979     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20980         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20981         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20982         MMXSrcOp.getValueType() == MVT::v1i64 &&
20983         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20984       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20985                          N->getValueType(0),
20986                          MMXSrcOp.getOperand(0));
20987   }
20988
20989   EVT VT = N->getValueType(0);
20990   
20991   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
20992       InputVector.getOpcode() == ISD::BITCAST &&
20993       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
20994     uint64_t ExtractedElt =
20995           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20996     uint64_t InputValue =
20997           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
20998     uint64_t Res = (InputValue >> ExtractedElt) & 1;
20999     return DAG.getConstant(Res, dl, MVT::i1);
21000   }
21001   // Only operate on vectors of 4 elements, where the alternative shuffling
21002   // gets to be more expensive.
21003   if (InputVector.getValueType() != MVT::v4i32)
21004     return SDValue();
21005
21006   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21007   // single use which is a sign-extend or zero-extend, and all elements are
21008   // used.
21009   SmallVector<SDNode *, 4> Uses;
21010   unsigned ExtractedElements = 0;
21011   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21012        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21013     if (UI.getUse().getResNo() != InputVector.getResNo())
21014       return SDValue();
21015
21016     SDNode *Extract = *UI;
21017     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21018       return SDValue();
21019
21020     if (Extract->getValueType(0) != MVT::i32)
21021       return SDValue();
21022     if (!Extract->hasOneUse())
21023       return SDValue();
21024     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21025         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21026       return SDValue();
21027     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21028       return SDValue();
21029
21030     // Record which element was extracted.
21031     ExtractedElements |=
21032       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21033
21034     Uses.push_back(Extract);
21035   }
21036
21037   // If not all the elements were used, this may not be worthwhile.
21038   if (ExtractedElements != 15)
21039     return SDValue();
21040
21041   // Ok, we've now decided to do the transformation.
21042   // If 64-bit shifts are legal, use the extract-shift sequence,
21043   // otherwise bounce the vector off the cache.
21044   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21045   SDValue Vals[4];
21046
21047   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21048     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
21049     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
21050     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21051       DAG.getConstant(0, dl, VecIdxTy));
21052     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21053       DAG.getConstant(1, dl, VecIdxTy));
21054
21055     SDValue ShAmt = DAG.getConstant(32, dl,
21056       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
21057     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21058     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21059       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21060     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21061     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21062       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21063   } else {
21064     // Store the value to a temporary stack slot.
21065     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21066     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21067       MachinePointerInfo(), false, false, 0);
21068
21069     EVT ElementType = InputVector.getValueType().getVectorElementType();
21070     unsigned EltSize = ElementType.getSizeInBits() / 8;
21071
21072     // Replace each use (extract) with a load of the appropriate element.
21073     for (unsigned i = 0; i < 4; ++i) {
21074       uint64_t Offset = EltSize * i;
21075       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21076
21077       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21078                                        StackPtr, OffsetVal);
21079
21080       // Load the scalar.
21081       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21082                             ScalarAddr, MachinePointerInfo(),
21083                             false, false, false, 0);
21084
21085     }
21086   }
21087
21088   // Replace the extracts
21089   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21090     UE = Uses.end(); UI != UE; ++UI) {
21091     SDNode *Extract = *UI;
21092
21093     SDValue Idx = Extract->getOperand(1);
21094     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21095     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21096   }
21097
21098   // The replacement was made in place; don't return anything.
21099   return SDValue();
21100 }
21101
21102 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21103 static std::pair<unsigned, bool>
21104 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21105                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21106   if (!VT.isVector())
21107     return std::make_pair(0, false);
21108
21109   bool NeedSplit = false;
21110   switch (VT.getSimpleVT().SimpleTy) {
21111   default: return std::make_pair(0, false);
21112   case MVT::v4i64:
21113   case MVT::v2i64:
21114     if (!Subtarget->hasVLX())
21115       return std::make_pair(0, false);
21116     break;
21117   case MVT::v64i8:
21118   case MVT::v32i16:
21119     if (!Subtarget->hasBWI())
21120       return std::make_pair(0, false);
21121     break;
21122   case MVT::v16i32:
21123   case MVT::v8i64:
21124     if (!Subtarget->hasAVX512())
21125       return std::make_pair(0, false);
21126     break;
21127   case MVT::v32i8:
21128   case MVT::v16i16:
21129   case MVT::v8i32:
21130     if (!Subtarget->hasAVX2())
21131       NeedSplit = true;
21132     if (!Subtarget->hasAVX())
21133       return std::make_pair(0, false);
21134     break;
21135   case MVT::v16i8:
21136   case MVT::v8i16:
21137   case MVT::v4i32:
21138     if (!Subtarget->hasSSE2())
21139       return std::make_pair(0, false);
21140   }
21141
21142   // SSE2 has only a small subset of the operations.
21143   bool hasUnsigned = Subtarget->hasSSE41() ||
21144                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21145   bool hasSigned = Subtarget->hasSSE41() ||
21146                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21147
21148   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21149
21150   unsigned Opc = 0;
21151   // Check for x CC y ? x : y.
21152   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21153       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21154     switch (CC) {
21155     default: break;
21156     case ISD::SETULT:
21157     case ISD::SETULE:
21158       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21159     case ISD::SETUGT:
21160     case ISD::SETUGE:
21161       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21162     case ISD::SETLT:
21163     case ISD::SETLE:
21164       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21165     case ISD::SETGT:
21166     case ISD::SETGE:
21167       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21168     }
21169   // Check for x CC y ? y : x -- a min/max with reversed arms.
21170   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21171              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21172     switch (CC) {
21173     default: break;
21174     case ISD::SETULT:
21175     case ISD::SETULE:
21176       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21177     case ISD::SETUGT:
21178     case ISD::SETUGE:
21179       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21180     case ISD::SETLT:
21181     case ISD::SETLE:
21182       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21183     case ISD::SETGT:
21184     case ISD::SETGE:
21185       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21186     }
21187   }
21188
21189   return std::make_pair(Opc, NeedSplit);
21190 }
21191
21192 static SDValue
21193 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21194                                       const X86Subtarget *Subtarget) {
21195   SDLoc dl(N);
21196   SDValue Cond = N->getOperand(0);
21197   SDValue LHS = N->getOperand(1);
21198   SDValue RHS = N->getOperand(2);
21199
21200   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21201     SDValue CondSrc = Cond->getOperand(0);
21202     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21203       Cond = CondSrc->getOperand(0);
21204   }
21205
21206   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21207     return SDValue();
21208
21209   // A vselect where all conditions and data are constants can be optimized into
21210   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21211   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21212       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21213     return SDValue();
21214
21215   unsigned MaskValue = 0;
21216   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21217     return SDValue();
21218
21219   MVT VT = N->getSimpleValueType(0);
21220   unsigned NumElems = VT.getVectorNumElements();
21221   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21222   for (unsigned i = 0; i < NumElems; ++i) {
21223     // Be sure we emit undef where we can.
21224     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21225       ShuffleMask[i] = -1;
21226     else
21227       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21228   }
21229
21230   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21231   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21232     return SDValue();
21233   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21234 }
21235
21236 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21237 /// nodes.
21238 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21239                                     TargetLowering::DAGCombinerInfo &DCI,
21240                                     const X86Subtarget *Subtarget) {
21241   SDLoc DL(N);
21242   SDValue Cond = N->getOperand(0);
21243   // Get the LHS/RHS of the select.
21244   SDValue LHS = N->getOperand(1);
21245   SDValue RHS = N->getOperand(2);
21246   EVT VT = LHS.getValueType();
21247   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21248
21249   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21250   // instructions match the semantics of the common C idiom x<y?x:y but not
21251   // x<=y?x:y, because of how they handle negative zero (which can be
21252   // ignored in unsafe-math mode).
21253   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21254   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21255       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21256       (Subtarget->hasSSE2() ||
21257        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21258     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21259
21260     unsigned Opcode = 0;
21261     // Check for x CC y ? x : y.
21262     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21263         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21264       switch (CC) {
21265       default: break;
21266       case ISD::SETULT:
21267         // Converting this to a min would handle NaNs incorrectly, and swapping
21268         // the operands would cause it to handle comparisons between positive
21269         // and negative zero incorrectly.
21270         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21271           if (!DAG.getTarget().Options.UnsafeFPMath &&
21272               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21273             break;
21274           std::swap(LHS, RHS);
21275         }
21276         Opcode = X86ISD::FMIN;
21277         break;
21278       case ISD::SETOLE:
21279         // Converting this to a min would handle comparisons between positive
21280         // and negative zero incorrectly.
21281         if (!DAG.getTarget().Options.UnsafeFPMath &&
21282             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21283           break;
21284         Opcode = X86ISD::FMIN;
21285         break;
21286       case ISD::SETULE:
21287         // Converting this to a min would handle both negative zeros and NaNs
21288         // incorrectly, but we can swap the operands to fix both.
21289         std::swap(LHS, RHS);
21290       case ISD::SETOLT:
21291       case ISD::SETLT:
21292       case ISD::SETLE:
21293         Opcode = X86ISD::FMIN;
21294         break;
21295
21296       case ISD::SETOGE:
21297         // Converting this to a max would handle comparisons between positive
21298         // and negative zero incorrectly.
21299         if (!DAG.getTarget().Options.UnsafeFPMath &&
21300             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21301           break;
21302         Opcode = X86ISD::FMAX;
21303         break;
21304       case ISD::SETUGT:
21305         // Converting this to a max would handle NaNs incorrectly, and swapping
21306         // the operands would cause it to handle comparisons between positive
21307         // and negative zero incorrectly.
21308         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21309           if (!DAG.getTarget().Options.UnsafeFPMath &&
21310               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21311             break;
21312           std::swap(LHS, RHS);
21313         }
21314         Opcode = X86ISD::FMAX;
21315         break;
21316       case ISD::SETUGE:
21317         // Converting this to a max would handle both negative zeros and NaNs
21318         // incorrectly, but we can swap the operands to fix both.
21319         std::swap(LHS, RHS);
21320       case ISD::SETOGT:
21321       case ISD::SETGT:
21322       case ISD::SETGE:
21323         Opcode = X86ISD::FMAX;
21324         break;
21325       }
21326     // Check for x CC y ? y : x -- a min/max with reversed arms.
21327     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21328                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21329       switch (CC) {
21330       default: break;
21331       case ISD::SETOGE:
21332         // Converting this to a min would handle comparisons between positive
21333         // and negative zero incorrectly, and swapping the operands would
21334         // cause it to handle NaNs incorrectly.
21335         if (!DAG.getTarget().Options.UnsafeFPMath &&
21336             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21337           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21338             break;
21339           std::swap(LHS, RHS);
21340         }
21341         Opcode = X86ISD::FMIN;
21342         break;
21343       case ISD::SETUGT:
21344         // Converting this to a min would handle NaNs incorrectly.
21345         if (!DAG.getTarget().Options.UnsafeFPMath &&
21346             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21347           break;
21348         Opcode = X86ISD::FMIN;
21349         break;
21350       case ISD::SETUGE:
21351         // Converting this to a min would handle both negative zeros and NaNs
21352         // incorrectly, but we can swap the operands to fix both.
21353         std::swap(LHS, RHS);
21354       case ISD::SETOGT:
21355       case ISD::SETGT:
21356       case ISD::SETGE:
21357         Opcode = X86ISD::FMIN;
21358         break;
21359
21360       case ISD::SETULT:
21361         // Converting this to a max would handle NaNs incorrectly.
21362         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21363           break;
21364         Opcode = X86ISD::FMAX;
21365         break;
21366       case ISD::SETOLE:
21367         // Converting this to a max would handle comparisons between positive
21368         // and negative zero incorrectly, and swapping the operands would
21369         // cause it to handle NaNs incorrectly.
21370         if (!DAG.getTarget().Options.UnsafeFPMath &&
21371             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21372           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21373             break;
21374           std::swap(LHS, RHS);
21375         }
21376         Opcode = X86ISD::FMAX;
21377         break;
21378       case ISD::SETULE:
21379         // Converting this to a max would handle both negative zeros and NaNs
21380         // incorrectly, but we can swap the operands to fix both.
21381         std::swap(LHS, RHS);
21382       case ISD::SETOLT:
21383       case ISD::SETLT:
21384       case ISD::SETLE:
21385         Opcode = X86ISD::FMAX;
21386         break;
21387       }
21388     }
21389
21390     if (Opcode)
21391       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21392   }
21393
21394   EVT CondVT = Cond.getValueType();
21395   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21396       CondVT.getVectorElementType() == MVT::i1) {
21397     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21398     // lowering on KNL. In this case we convert it to
21399     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21400     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21401     // Since SKX these selects have a proper lowering.
21402     EVT OpVT = LHS.getValueType();
21403     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21404         (OpVT.getVectorElementType() == MVT::i8 ||
21405          OpVT.getVectorElementType() == MVT::i16) &&
21406         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21407       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21408       DCI.AddToWorklist(Cond.getNode());
21409       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21410     }
21411   }
21412   // If this is a select between two integer constants, try to do some
21413   // optimizations.
21414   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21415     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21416       // Don't do this for crazy integer types.
21417       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21418         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21419         // so that TrueC (the true value) is larger than FalseC.
21420         bool NeedsCondInvert = false;
21421
21422         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21423             // Efficiently invertible.
21424             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21425              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21426               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21427           NeedsCondInvert = true;
21428           std::swap(TrueC, FalseC);
21429         }
21430
21431         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21432         if (FalseC->getAPIntValue() == 0 &&
21433             TrueC->getAPIntValue().isPowerOf2()) {
21434           if (NeedsCondInvert) // Invert the condition if needed.
21435             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21436                                DAG.getConstant(1, DL, Cond.getValueType()));
21437
21438           // Zero extend the condition if needed.
21439           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21440
21441           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21442           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21443                              DAG.getConstant(ShAmt, DL, MVT::i8));
21444         }
21445
21446         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21447         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21448           if (NeedsCondInvert) // Invert the condition if needed.
21449             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21450                                DAG.getConstant(1, DL, Cond.getValueType()));
21451
21452           // Zero extend the condition if needed.
21453           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21454                              FalseC->getValueType(0), Cond);
21455           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21456                              SDValue(FalseC, 0));
21457         }
21458
21459         // Optimize cases that will turn into an LEA instruction.  This requires
21460         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21461         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21462           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21463           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21464
21465           bool isFastMultiplier = false;
21466           if (Diff < 10) {
21467             switch ((unsigned char)Diff) {
21468               default: break;
21469               case 1:  // result = add base, cond
21470               case 2:  // result = lea base(    , cond*2)
21471               case 3:  // result = lea base(cond, cond*2)
21472               case 4:  // result = lea base(    , cond*4)
21473               case 5:  // result = lea base(cond, cond*4)
21474               case 8:  // result = lea base(    , cond*8)
21475               case 9:  // result = lea base(cond, cond*8)
21476                 isFastMultiplier = true;
21477                 break;
21478             }
21479           }
21480
21481           if (isFastMultiplier) {
21482             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21483             if (NeedsCondInvert) // Invert the condition if needed.
21484               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21485                                  DAG.getConstant(1, DL, Cond.getValueType()));
21486
21487             // Zero extend the condition if needed.
21488             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21489                                Cond);
21490             // Scale the condition by the difference.
21491             if (Diff != 1)
21492               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21493                                  DAG.getConstant(Diff, DL,
21494                                                  Cond.getValueType()));
21495
21496             // Add the base if non-zero.
21497             if (FalseC->getAPIntValue() != 0)
21498               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21499                                  SDValue(FalseC, 0));
21500             return Cond;
21501           }
21502         }
21503       }
21504   }
21505
21506   // Canonicalize max and min:
21507   // (x > y) ? x : y -> (x >= y) ? x : y
21508   // (x < y) ? x : y -> (x <= y) ? x : y
21509   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21510   // the need for an extra compare
21511   // against zero. e.g.
21512   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21513   // subl   %esi, %edi
21514   // testl  %edi, %edi
21515   // movl   $0, %eax
21516   // cmovgl %edi, %eax
21517   // =>
21518   // xorl   %eax, %eax
21519   // subl   %esi, $edi
21520   // cmovsl %eax, %edi
21521   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21522       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21523       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21524     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21525     switch (CC) {
21526     default: break;
21527     case ISD::SETLT:
21528     case ISD::SETGT: {
21529       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21530       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21531                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21532       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21533     }
21534     }
21535   }
21536
21537   // Early exit check
21538   if (!TLI.isTypeLegal(VT))
21539     return SDValue();
21540
21541   // Match VSELECTs into subs with unsigned saturation.
21542   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21543       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21544       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21545        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21546     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21547
21548     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21549     // left side invert the predicate to simplify logic below.
21550     SDValue Other;
21551     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21552       Other = RHS;
21553       CC = ISD::getSetCCInverse(CC, true);
21554     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21555       Other = LHS;
21556     }
21557
21558     if (Other.getNode() && Other->getNumOperands() == 2 &&
21559         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21560       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21561       SDValue CondRHS = Cond->getOperand(1);
21562
21563       // Look for a general sub with unsigned saturation first.
21564       // x >= y ? x-y : 0 --> subus x, y
21565       // x >  y ? x-y : 0 --> subus x, y
21566       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21567           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21568         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21569
21570       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21571         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21572           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21573             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21574               // If the RHS is a constant we have to reverse the const
21575               // canonicalization.
21576               // x > C-1 ? x+-C : 0 --> subus x, C
21577               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21578                   CondRHSConst->getAPIntValue() ==
21579                       (-OpRHSConst->getAPIntValue() - 1))
21580                 return DAG.getNode(
21581                     X86ISD::SUBUS, DL, VT, OpLHS,
21582                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21583
21584           // Another special case: If C was a sign bit, the sub has been
21585           // canonicalized into a xor.
21586           // FIXME: Would it be better to use computeKnownBits to determine
21587           //        whether it's safe to decanonicalize the xor?
21588           // x s< 0 ? x^C : 0 --> subus x, C
21589           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21590               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21591               OpRHSConst->getAPIntValue().isSignBit())
21592             // Note that we have to rebuild the RHS constant here to ensure we
21593             // don't rely on particular values of undef lanes.
21594             return DAG.getNode(
21595                 X86ISD::SUBUS, DL, VT, OpLHS,
21596                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21597         }
21598     }
21599   }
21600
21601   // Try to match a min/max vector operation.
21602   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21603     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21604     unsigned Opc = ret.first;
21605     bool NeedSplit = ret.second;
21606
21607     if (Opc && NeedSplit) {
21608       unsigned NumElems = VT.getVectorNumElements();
21609       // Extract the LHS vectors
21610       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21611       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21612
21613       // Extract the RHS vectors
21614       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21615       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21616
21617       // Create min/max for each subvector
21618       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21619       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21620
21621       // Merge the result
21622       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21623     } else if (Opc)
21624       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21625   }
21626
21627   // Simplify vector selection if condition value type matches vselect
21628   // operand type
21629   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21630     assert(Cond.getValueType().isVector() &&
21631            "vector select expects a vector selector!");
21632
21633     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21634     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21635
21636     // Try invert the condition if true value is not all 1s and false value
21637     // is not all 0s.
21638     if (!TValIsAllOnes && !FValIsAllZeros &&
21639         // Check if the selector will be produced by CMPP*/PCMP*
21640         Cond.getOpcode() == ISD::SETCC &&
21641         // Check if SETCC has already been promoted
21642         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21643       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21644       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21645
21646       if (TValIsAllZeros || FValIsAllOnes) {
21647         SDValue CC = Cond.getOperand(2);
21648         ISD::CondCode NewCC =
21649           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21650                                Cond.getOperand(0).getValueType().isInteger());
21651         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21652         std::swap(LHS, RHS);
21653         TValIsAllOnes = FValIsAllOnes;
21654         FValIsAllZeros = TValIsAllZeros;
21655       }
21656     }
21657
21658     if (TValIsAllOnes || FValIsAllZeros) {
21659       SDValue Ret;
21660
21661       if (TValIsAllOnes && FValIsAllZeros)
21662         Ret = Cond;
21663       else if (TValIsAllOnes)
21664         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21665                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21666       else if (FValIsAllZeros)
21667         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21668                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21669
21670       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21671     }
21672   }
21673
21674   // We should generate an X86ISD::BLENDI from a vselect if its argument
21675   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21676   // constants. This specific pattern gets generated when we split a
21677   // selector for a 512 bit vector in a machine without AVX512 (but with
21678   // 256-bit vectors), during legalization:
21679   //
21680   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21681   //
21682   // Iff we find this pattern and the build_vectors are built from
21683   // constants, we translate the vselect into a shuffle_vector that we
21684   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21685   if ((N->getOpcode() == ISD::VSELECT ||
21686        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21687       !DCI.isBeforeLegalize()) {
21688     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21689     if (Shuffle.getNode())
21690       return Shuffle;
21691   }
21692
21693   // If this is a *dynamic* select (non-constant condition) and we can match
21694   // this node with one of the variable blend instructions, restructure the
21695   // condition so that the blends can use the high bit of each element and use
21696   // SimplifyDemandedBits to simplify the condition operand.
21697   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21698       !DCI.isBeforeLegalize() &&
21699       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21700     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21701
21702     // Don't optimize vector selects that map to mask-registers.
21703     if (BitWidth == 1)
21704       return SDValue();
21705
21706     // We can only handle the cases where VSELECT is directly legal on the
21707     // subtarget. We custom lower VSELECT nodes with constant conditions and
21708     // this makes it hard to see whether a dynamic VSELECT will correctly
21709     // lower, so we both check the operation's status and explicitly handle the
21710     // cases where a *dynamic* blend will fail even though a constant-condition
21711     // blend could be custom lowered.
21712     // FIXME: We should find a better way to handle this class of problems.
21713     // Potentially, we should combine constant-condition vselect nodes
21714     // pre-legalization into shuffles and not mark as many types as custom
21715     // lowered.
21716     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21717       return SDValue();
21718     // FIXME: We don't support i16-element blends currently. We could and
21719     // should support them by making *all* the bits in the condition be set
21720     // rather than just the high bit and using an i8-element blend.
21721     if (VT.getScalarType() == MVT::i16)
21722       return SDValue();
21723     // Dynamic blending was only available from SSE4.1 onward.
21724     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21725       return SDValue();
21726     // Byte blends are only available in AVX2
21727     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21728         !Subtarget->hasAVX2())
21729       return SDValue();
21730
21731     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21732     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21733
21734     APInt KnownZero, KnownOne;
21735     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21736                                           DCI.isBeforeLegalizeOps());
21737     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21738         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21739                                  TLO)) {
21740       // If we changed the computation somewhere in the DAG, this change
21741       // will affect all users of Cond.
21742       // Make sure it is fine and update all the nodes so that we do not
21743       // use the generic VSELECT anymore. Otherwise, we may perform
21744       // wrong optimizations as we messed up with the actual expectation
21745       // for the vector boolean values.
21746       if (Cond != TLO.Old) {
21747         // Check all uses of that condition operand to check whether it will be
21748         // consumed by non-BLEND instructions, which may depend on all bits are
21749         // set properly.
21750         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21751              I != E; ++I)
21752           if (I->getOpcode() != ISD::VSELECT)
21753             // TODO: Add other opcodes eventually lowered into BLEND.
21754             return SDValue();
21755
21756         // Update all the users of the condition, before committing the change,
21757         // so that the VSELECT optimizations that expect the correct vector
21758         // boolean value will not be triggered.
21759         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21760              I != E; ++I)
21761           DAG.ReplaceAllUsesOfValueWith(
21762               SDValue(*I, 0),
21763               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21764                           Cond, I->getOperand(1), I->getOperand(2)));
21765         DCI.CommitTargetLoweringOpt(TLO);
21766         return SDValue();
21767       }
21768       // At this point, only Cond is changed. Change the condition
21769       // just for N to keep the opportunity to optimize all other
21770       // users their own way.
21771       DAG.ReplaceAllUsesOfValueWith(
21772           SDValue(N, 0),
21773           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21774                       TLO.New, N->getOperand(1), N->getOperand(2)));
21775       return SDValue();
21776     }
21777   }
21778
21779   return SDValue();
21780 }
21781
21782 // Check whether a boolean test is testing a boolean value generated by
21783 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21784 // code.
21785 //
21786 // Simplify the following patterns:
21787 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21788 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21789 // to (Op EFLAGS Cond)
21790 //
21791 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21792 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21793 // to (Op EFLAGS !Cond)
21794 //
21795 // where Op could be BRCOND or CMOV.
21796 //
21797 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21798   // Quit if not CMP and SUB with its value result used.
21799   if (Cmp.getOpcode() != X86ISD::CMP &&
21800       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21801       return SDValue();
21802
21803   // Quit if not used as a boolean value.
21804   if (CC != X86::COND_E && CC != X86::COND_NE)
21805     return SDValue();
21806
21807   // Check CMP operands. One of them should be 0 or 1 and the other should be
21808   // an SetCC or extended from it.
21809   SDValue Op1 = Cmp.getOperand(0);
21810   SDValue Op2 = Cmp.getOperand(1);
21811
21812   SDValue SetCC;
21813   const ConstantSDNode* C = nullptr;
21814   bool needOppositeCond = (CC == X86::COND_E);
21815   bool checkAgainstTrue = false; // Is it a comparison against 1?
21816
21817   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21818     SetCC = Op2;
21819   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21820     SetCC = Op1;
21821   else // Quit if all operands are not constants.
21822     return SDValue();
21823
21824   if (C->getZExtValue() == 1) {
21825     needOppositeCond = !needOppositeCond;
21826     checkAgainstTrue = true;
21827   } else if (C->getZExtValue() != 0)
21828     // Quit if the constant is neither 0 or 1.
21829     return SDValue();
21830
21831   bool truncatedToBoolWithAnd = false;
21832   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21833   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21834          SetCC.getOpcode() == ISD::TRUNCATE ||
21835          SetCC.getOpcode() == ISD::AND) {
21836     if (SetCC.getOpcode() == ISD::AND) {
21837       int OpIdx = -1;
21838       ConstantSDNode *CS;
21839       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21840           CS->getZExtValue() == 1)
21841         OpIdx = 1;
21842       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21843           CS->getZExtValue() == 1)
21844         OpIdx = 0;
21845       if (OpIdx == -1)
21846         break;
21847       SetCC = SetCC.getOperand(OpIdx);
21848       truncatedToBoolWithAnd = true;
21849     } else
21850       SetCC = SetCC.getOperand(0);
21851   }
21852
21853   switch (SetCC.getOpcode()) {
21854   case X86ISD::SETCC_CARRY:
21855     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21856     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21857     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21858     // truncated to i1 using 'and'.
21859     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21860       break;
21861     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21862            "Invalid use of SETCC_CARRY!");
21863     // FALL THROUGH
21864   case X86ISD::SETCC:
21865     // Set the condition code or opposite one if necessary.
21866     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21867     if (needOppositeCond)
21868       CC = X86::GetOppositeBranchCondition(CC);
21869     return SetCC.getOperand(1);
21870   case X86ISD::CMOV: {
21871     // Check whether false/true value has canonical one, i.e. 0 or 1.
21872     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21873     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21874     // Quit if true value is not a constant.
21875     if (!TVal)
21876       return SDValue();
21877     // Quit if false value is not a constant.
21878     if (!FVal) {
21879       SDValue Op = SetCC.getOperand(0);
21880       // Skip 'zext' or 'trunc' node.
21881       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21882           Op.getOpcode() == ISD::TRUNCATE)
21883         Op = Op.getOperand(0);
21884       // A special case for rdrand/rdseed, where 0 is set if false cond is
21885       // found.
21886       if ((Op.getOpcode() != X86ISD::RDRAND &&
21887            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21888         return SDValue();
21889     }
21890     // Quit if false value is not the constant 0 or 1.
21891     bool FValIsFalse = true;
21892     if (FVal && FVal->getZExtValue() != 0) {
21893       if (FVal->getZExtValue() != 1)
21894         return SDValue();
21895       // If FVal is 1, opposite cond is needed.
21896       needOppositeCond = !needOppositeCond;
21897       FValIsFalse = false;
21898     }
21899     // Quit if TVal is not the constant opposite of FVal.
21900     if (FValIsFalse && TVal->getZExtValue() != 1)
21901       return SDValue();
21902     if (!FValIsFalse && TVal->getZExtValue() != 0)
21903       return SDValue();
21904     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21905     if (needOppositeCond)
21906       CC = X86::GetOppositeBranchCondition(CC);
21907     return SetCC.getOperand(3);
21908   }
21909   }
21910
21911   return SDValue();
21912 }
21913
21914 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21915 /// Match:
21916 ///   (X86or (X86setcc) (X86setcc))
21917 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21918 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21919                                            X86::CondCode &CC1, SDValue &Flags,
21920                                            bool &isAnd) {
21921   if (Cond->getOpcode() == X86ISD::CMP) {
21922     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21923     if (!CondOp1C || !CondOp1C->isNullValue())
21924       return false;
21925
21926     Cond = Cond->getOperand(0);
21927   }
21928
21929   isAnd = false;
21930
21931   SDValue SetCC0, SetCC1;
21932   switch (Cond->getOpcode()) {
21933   default: return false;
21934   case ISD::AND:
21935   case X86ISD::AND:
21936     isAnd = true;
21937     // fallthru
21938   case ISD::OR:
21939   case X86ISD::OR:
21940     SetCC0 = Cond->getOperand(0);
21941     SetCC1 = Cond->getOperand(1);
21942     break;
21943   };
21944
21945   // Make sure we have SETCC nodes, using the same flags value.
21946   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21947       SetCC1.getOpcode() != X86ISD::SETCC ||
21948       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21949     return false;
21950
21951   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21952   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21953   Flags = SetCC0->getOperand(1);
21954   return true;
21955 }
21956
21957 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21958 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21959                                   TargetLowering::DAGCombinerInfo &DCI,
21960                                   const X86Subtarget *Subtarget) {
21961   SDLoc DL(N);
21962
21963   // If the flag operand isn't dead, don't touch this CMOV.
21964   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21965     return SDValue();
21966
21967   SDValue FalseOp = N->getOperand(0);
21968   SDValue TrueOp = N->getOperand(1);
21969   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21970   SDValue Cond = N->getOperand(3);
21971
21972   if (CC == X86::COND_E || CC == X86::COND_NE) {
21973     switch (Cond.getOpcode()) {
21974     default: break;
21975     case X86ISD::BSR:
21976     case X86ISD::BSF:
21977       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21978       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21979         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21980     }
21981   }
21982
21983   SDValue Flags;
21984
21985   Flags = checkBoolTestSetCCCombine(Cond, CC);
21986   if (Flags.getNode() &&
21987       // Extra check as FCMOV only supports a subset of X86 cond.
21988       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21989     SDValue Ops[] = { FalseOp, TrueOp,
21990                       DAG.getConstant(CC, DL, MVT::i8), Flags };
21991     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21992   }
21993
21994   // If this is a select between two integer constants, try to do some
21995   // optimizations.  Note that the operands are ordered the opposite of SELECT
21996   // operands.
21997   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21998     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21999       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22000       // larger than FalseC (the false value).
22001       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22002         CC = X86::GetOppositeBranchCondition(CC);
22003         std::swap(TrueC, FalseC);
22004         std::swap(TrueOp, FalseOp);
22005       }
22006
22007       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22008       // This is efficient for any integer data type (including i8/i16) and
22009       // shift amount.
22010       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22011         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22012                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22013
22014         // Zero extend the condition if needed.
22015         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22016
22017         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22018         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22019                            DAG.getConstant(ShAmt, DL, MVT::i8));
22020         if (N->getNumValues() == 2)  // Dead flag value?
22021           return DCI.CombineTo(N, Cond, SDValue());
22022         return Cond;
22023       }
22024
22025       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22026       // for any integer data type, including i8/i16.
22027       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22028         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22029                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22030
22031         // Zero extend the condition if needed.
22032         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22033                            FalseC->getValueType(0), Cond);
22034         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22035                            SDValue(FalseC, 0));
22036
22037         if (N->getNumValues() == 2)  // Dead flag value?
22038           return DCI.CombineTo(N, Cond, SDValue());
22039         return Cond;
22040       }
22041
22042       // Optimize cases that will turn into an LEA instruction.  This requires
22043       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22044       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22045         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22046         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22047
22048         bool isFastMultiplier = false;
22049         if (Diff < 10) {
22050           switch ((unsigned char)Diff) {
22051           default: break;
22052           case 1:  // result = add base, cond
22053           case 2:  // result = lea base(    , cond*2)
22054           case 3:  // result = lea base(cond, cond*2)
22055           case 4:  // result = lea base(    , cond*4)
22056           case 5:  // result = lea base(cond, cond*4)
22057           case 8:  // result = lea base(    , cond*8)
22058           case 9:  // result = lea base(cond, cond*8)
22059             isFastMultiplier = true;
22060             break;
22061           }
22062         }
22063
22064         if (isFastMultiplier) {
22065           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22066           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22067                              DAG.getConstant(CC, DL, MVT::i8), Cond);
22068           // Zero extend the condition if needed.
22069           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22070                              Cond);
22071           // Scale the condition by the difference.
22072           if (Diff != 1)
22073             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22074                                DAG.getConstant(Diff, DL, Cond.getValueType()));
22075
22076           // Add the base if non-zero.
22077           if (FalseC->getAPIntValue() != 0)
22078             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22079                                SDValue(FalseC, 0));
22080           if (N->getNumValues() == 2)  // Dead flag value?
22081             return DCI.CombineTo(N, Cond, SDValue());
22082           return Cond;
22083         }
22084       }
22085     }
22086   }
22087
22088   // Handle these cases:
22089   //   (select (x != c), e, c) -> select (x != c), e, x),
22090   //   (select (x == c), c, e) -> select (x == c), x, e)
22091   // where the c is an integer constant, and the "select" is the combination
22092   // of CMOV and CMP.
22093   //
22094   // The rationale for this change is that the conditional-move from a constant
22095   // needs two instructions, however, conditional-move from a register needs
22096   // only one instruction.
22097   //
22098   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22099   //  some instruction-combining opportunities. This opt needs to be
22100   //  postponed as late as possible.
22101   //
22102   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22103     // the DCI.xxxx conditions are provided to postpone the optimization as
22104     // late as possible.
22105
22106     ConstantSDNode *CmpAgainst = nullptr;
22107     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22108         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22109         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22110
22111       if (CC == X86::COND_NE &&
22112           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22113         CC = X86::GetOppositeBranchCondition(CC);
22114         std::swap(TrueOp, FalseOp);
22115       }
22116
22117       if (CC == X86::COND_E &&
22118           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22119         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22120                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22121         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22122       }
22123     }
22124   }
22125
22126   // Fold and/or of setcc's to double CMOV:
22127   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22128   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22129   //
22130   // This combine lets us generate:
22131   //   cmovcc1 (jcc1 if we don't have CMOV)
22132   //   cmovcc2 (same)
22133   // instead of:
22134   //   setcc1
22135   //   setcc2
22136   //   and/or
22137   //   cmovne (jne if we don't have CMOV)
22138   // When we can't use the CMOV instruction, it might increase branch
22139   // mispredicts.
22140   // When we can use CMOV, or when there is no mispredict, this improves
22141   // throughput and reduces register pressure.
22142   //
22143   if (CC == X86::COND_NE) {
22144     SDValue Flags;
22145     X86::CondCode CC0, CC1;
22146     bool isAndSetCC;
22147     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22148       if (isAndSetCC) {
22149         std::swap(FalseOp, TrueOp);
22150         CC0 = X86::GetOppositeBranchCondition(CC0);
22151         CC1 = X86::GetOppositeBranchCondition(CC1);
22152       }
22153
22154       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22155         Flags};
22156       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22157       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22158       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22159       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22160       return CMOV;
22161     }
22162   }
22163
22164   return SDValue();
22165 }
22166
22167 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22168                                                 const X86Subtarget *Subtarget) {
22169   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22170   switch (IntNo) {
22171   default: return SDValue();
22172   // SSE/AVX/AVX2 blend intrinsics.
22173   case Intrinsic::x86_avx2_pblendvb:
22174     // Don't try to simplify this intrinsic if we don't have AVX2.
22175     if (!Subtarget->hasAVX2())
22176       return SDValue();
22177     // FALL-THROUGH
22178   case Intrinsic::x86_avx_blendv_pd_256:
22179   case Intrinsic::x86_avx_blendv_ps_256:
22180     // Don't try to simplify this intrinsic if we don't have AVX.
22181     if (!Subtarget->hasAVX())
22182       return SDValue();
22183     // FALL-THROUGH
22184   case Intrinsic::x86_sse41_blendvps:
22185   case Intrinsic::x86_sse41_blendvpd:
22186   case Intrinsic::x86_sse41_pblendvb: {
22187     SDValue Op0 = N->getOperand(1);
22188     SDValue Op1 = N->getOperand(2);
22189     SDValue Mask = N->getOperand(3);
22190
22191     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22192     if (!Subtarget->hasSSE41())
22193       return SDValue();
22194
22195     // fold (blend A, A, Mask) -> A
22196     if (Op0 == Op1)
22197       return Op0;
22198     // fold (blend A, B, allZeros) -> A
22199     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22200       return Op0;
22201     // fold (blend A, B, allOnes) -> B
22202     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22203       return Op1;
22204
22205     // Simplify the case where the mask is a constant i32 value.
22206     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22207       if (C->isNullValue())
22208         return Op0;
22209       if (C->isAllOnesValue())
22210         return Op1;
22211     }
22212
22213     return SDValue();
22214   }
22215
22216   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22217   case Intrinsic::x86_sse2_psrai_w:
22218   case Intrinsic::x86_sse2_psrai_d:
22219   case Intrinsic::x86_avx2_psrai_w:
22220   case Intrinsic::x86_avx2_psrai_d:
22221   case Intrinsic::x86_sse2_psra_w:
22222   case Intrinsic::x86_sse2_psra_d:
22223   case Intrinsic::x86_avx2_psra_w:
22224   case Intrinsic::x86_avx2_psra_d: {
22225     SDValue Op0 = N->getOperand(1);
22226     SDValue Op1 = N->getOperand(2);
22227     EVT VT = Op0.getValueType();
22228     assert(VT.isVector() && "Expected a vector type!");
22229
22230     if (isa<BuildVectorSDNode>(Op1))
22231       Op1 = Op1.getOperand(0);
22232
22233     if (!isa<ConstantSDNode>(Op1))
22234       return SDValue();
22235
22236     EVT SVT = VT.getVectorElementType();
22237     unsigned SVTBits = SVT.getSizeInBits();
22238
22239     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22240     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22241     uint64_t ShAmt = C.getZExtValue();
22242
22243     // Don't try to convert this shift into a ISD::SRA if the shift
22244     // count is bigger than or equal to the element size.
22245     if (ShAmt >= SVTBits)
22246       return SDValue();
22247
22248     // Trivial case: if the shift count is zero, then fold this
22249     // into the first operand.
22250     if (ShAmt == 0)
22251       return Op0;
22252
22253     // Replace this packed shift intrinsic with a target independent
22254     // shift dag node.
22255     SDLoc DL(N);
22256     SDValue Splat = DAG.getConstant(C, DL, VT);
22257     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22258   }
22259   }
22260 }
22261
22262 /// PerformMulCombine - Optimize a single multiply with constant into two
22263 /// in order to implement it with two cheaper instructions, e.g.
22264 /// LEA + SHL, LEA + LEA.
22265 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22266                                  TargetLowering::DAGCombinerInfo &DCI) {
22267   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22268     return SDValue();
22269
22270   EVT VT = N->getValueType(0);
22271   if (VT != MVT::i64 && VT != MVT::i32)
22272     return SDValue();
22273
22274   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22275   if (!C)
22276     return SDValue();
22277   uint64_t MulAmt = C->getZExtValue();
22278   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22279     return SDValue();
22280
22281   uint64_t MulAmt1 = 0;
22282   uint64_t MulAmt2 = 0;
22283   if ((MulAmt % 9) == 0) {
22284     MulAmt1 = 9;
22285     MulAmt2 = MulAmt / 9;
22286   } else if ((MulAmt % 5) == 0) {
22287     MulAmt1 = 5;
22288     MulAmt2 = MulAmt / 5;
22289   } else if ((MulAmt % 3) == 0) {
22290     MulAmt1 = 3;
22291     MulAmt2 = MulAmt / 3;
22292   }
22293   if (MulAmt2 &&
22294       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22295     SDLoc DL(N);
22296
22297     if (isPowerOf2_64(MulAmt2) &&
22298         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22299       // If second multiplifer is pow2, issue it first. We want the multiply by
22300       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22301       // is an add.
22302       std::swap(MulAmt1, MulAmt2);
22303
22304     SDValue NewMul;
22305     if (isPowerOf2_64(MulAmt1))
22306       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22307                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22308     else
22309       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22310                            DAG.getConstant(MulAmt1, DL, VT));
22311
22312     if (isPowerOf2_64(MulAmt2))
22313       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22314                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22315     else
22316       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22317                            DAG.getConstant(MulAmt2, DL, VT));
22318
22319     // Do not add new nodes to DAG combiner worklist.
22320     DCI.CombineTo(N, NewMul, false);
22321   }
22322   return SDValue();
22323 }
22324
22325 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22326   SDValue N0 = N->getOperand(0);
22327   SDValue N1 = N->getOperand(1);
22328   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22329   EVT VT = N0.getValueType();
22330
22331   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22332   // since the result of setcc_c is all zero's or all ones.
22333   if (VT.isInteger() && !VT.isVector() &&
22334       N1C && N0.getOpcode() == ISD::AND &&
22335       N0.getOperand(1).getOpcode() == ISD::Constant) {
22336     SDValue N00 = N0.getOperand(0);
22337     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22338         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22339           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22340          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22341       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22342       APInt ShAmt = N1C->getAPIntValue();
22343       Mask = Mask.shl(ShAmt);
22344       if (Mask != 0) {
22345         SDLoc DL(N);
22346         return DAG.getNode(ISD::AND, DL, VT,
22347                            N00, DAG.getConstant(Mask, DL, VT));
22348       }
22349     }
22350   }
22351
22352   // Hardware support for vector shifts is sparse which makes us scalarize the
22353   // vector operations in many cases. Also, on sandybridge ADD is faster than
22354   // shl.
22355   // (shl V, 1) -> add V,V
22356   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22357     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22358       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22359       // We shift all of the values by one. In many cases we do not have
22360       // hardware support for this operation. This is better expressed as an ADD
22361       // of two values.
22362       if (N1SplatC->getZExtValue() == 1)
22363         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22364     }
22365
22366   return SDValue();
22367 }
22368
22369 /// \brief Returns a vector of 0s if the node in input is a vector logical
22370 /// shift by a constant amount which is known to be bigger than or equal
22371 /// to the vector element size in bits.
22372 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22373                                       const X86Subtarget *Subtarget) {
22374   EVT VT = N->getValueType(0);
22375
22376   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22377       (!Subtarget->hasInt256() ||
22378        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22379     return SDValue();
22380
22381   SDValue Amt = N->getOperand(1);
22382   SDLoc DL(N);
22383   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22384     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22385       APInt ShiftAmt = AmtSplat->getAPIntValue();
22386       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22387
22388       // SSE2/AVX2 logical shifts always return a vector of 0s
22389       // if the shift amount is bigger than or equal to
22390       // the element size. The constant shift amount will be
22391       // encoded as a 8-bit immediate.
22392       if (ShiftAmt.trunc(8).uge(MaxAmount))
22393         return getZeroVector(VT, Subtarget, DAG, DL);
22394     }
22395
22396   return SDValue();
22397 }
22398
22399 /// PerformShiftCombine - Combine shifts.
22400 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22401                                    TargetLowering::DAGCombinerInfo &DCI,
22402                                    const X86Subtarget *Subtarget) {
22403   if (N->getOpcode() == ISD::SHL) {
22404     SDValue V = PerformSHLCombine(N, DAG);
22405     if (V.getNode()) return V;
22406   }
22407
22408   if (N->getOpcode() != ISD::SRA) {
22409     // Try to fold this logical shift into a zero vector.
22410     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22411     if (V.getNode()) return V;
22412   }
22413
22414   return SDValue();
22415 }
22416
22417 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22418 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22419 // and friends.  Likewise for OR -> CMPNEQSS.
22420 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22421                             TargetLowering::DAGCombinerInfo &DCI,
22422                             const X86Subtarget *Subtarget) {
22423   unsigned opcode;
22424
22425   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22426   // we're requiring SSE2 for both.
22427   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22428     SDValue N0 = N->getOperand(0);
22429     SDValue N1 = N->getOperand(1);
22430     SDValue CMP0 = N0->getOperand(1);
22431     SDValue CMP1 = N1->getOperand(1);
22432     SDLoc DL(N);
22433
22434     // The SETCCs should both refer to the same CMP.
22435     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22436       return SDValue();
22437
22438     SDValue CMP00 = CMP0->getOperand(0);
22439     SDValue CMP01 = CMP0->getOperand(1);
22440     EVT     VT    = CMP00.getValueType();
22441
22442     if (VT == MVT::f32 || VT == MVT::f64) {
22443       bool ExpectingFlags = false;
22444       // Check for any users that want flags:
22445       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22446            !ExpectingFlags && UI != UE; ++UI)
22447         switch (UI->getOpcode()) {
22448         default:
22449         case ISD::BR_CC:
22450         case ISD::BRCOND:
22451         case ISD::SELECT:
22452           ExpectingFlags = true;
22453           break;
22454         case ISD::CopyToReg:
22455         case ISD::SIGN_EXTEND:
22456         case ISD::ZERO_EXTEND:
22457         case ISD::ANY_EXTEND:
22458           break;
22459         }
22460
22461       if (!ExpectingFlags) {
22462         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22463         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22464
22465         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22466           X86::CondCode tmp = cc0;
22467           cc0 = cc1;
22468           cc1 = tmp;
22469         }
22470
22471         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22472             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22473           // FIXME: need symbolic constants for these magic numbers.
22474           // See X86ATTInstPrinter.cpp:printSSECC().
22475           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22476           if (Subtarget->hasAVX512()) {
22477             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22478                                          CMP01,
22479                                          DAG.getConstant(x86cc, DL, MVT::i8));
22480             if (N->getValueType(0) != MVT::i1)
22481               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22482                                  FSetCC);
22483             return FSetCC;
22484           }
22485           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22486                                               CMP00.getValueType(), CMP00, CMP01,
22487                                               DAG.getConstant(x86cc, DL,
22488                                                               MVT::i8));
22489
22490           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22491           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22492
22493           if (is64BitFP && !Subtarget->is64Bit()) {
22494             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22495             // 64-bit integer, since that's not a legal type. Since
22496             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22497             // bits, but can do this little dance to extract the lowest 32 bits
22498             // and work with those going forward.
22499             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22500                                            OnesOrZeroesF);
22501             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22502                                            Vector64);
22503             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22504                                         Vector32, DAG.getIntPtrConstant(0, DL));
22505             IntVT = MVT::i32;
22506           }
22507
22508           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22509                                               OnesOrZeroesF);
22510           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22511                                       DAG.getConstant(1, DL, IntVT));
22512           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22513                                               ANDed);
22514           return OneBitOfTruth;
22515         }
22516       }
22517     }
22518   }
22519   return SDValue();
22520 }
22521
22522 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22523 /// so it can be folded inside ANDNP.
22524 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22525   EVT VT = N->getValueType(0);
22526
22527   // Match direct AllOnes for 128 and 256-bit vectors
22528   if (ISD::isBuildVectorAllOnes(N))
22529     return true;
22530
22531   // Look through a bit convert.
22532   if (N->getOpcode() == ISD::BITCAST)
22533     N = N->getOperand(0).getNode();
22534
22535   // Sometimes the operand may come from a insert_subvector building a 256-bit
22536   // allones vector
22537   if (VT.is256BitVector() &&
22538       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22539     SDValue V1 = N->getOperand(0);
22540     SDValue V2 = N->getOperand(1);
22541
22542     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22543         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22544         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22545         ISD::isBuildVectorAllOnes(V2.getNode()))
22546       return true;
22547   }
22548
22549   return false;
22550 }
22551
22552 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22553 // register. In most cases we actually compare or select YMM-sized registers
22554 // and mixing the two types creates horrible code. This method optimizes
22555 // some of the transition sequences.
22556 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22557                                  TargetLowering::DAGCombinerInfo &DCI,
22558                                  const X86Subtarget *Subtarget) {
22559   EVT VT = N->getValueType(0);
22560   if (!VT.is256BitVector())
22561     return SDValue();
22562
22563   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22564           N->getOpcode() == ISD::ZERO_EXTEND ||
22565           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22566
22567   SDValue Narrow = N->getOperand(0);
22568   EVT NarrowVT = Narrow->getValueType(0);
22569   if (!NarrowVT.is128BitVector())
22570     return SDValue();
22571
22572   if (Narrow->getOpcode() != ISD::XOR &&
22573       Narrow->getOpcode() != ISD::AND &&
22574       Narrow->getOpcode() != ISD::OR)
22575     return SDValue();
22576
22577   SDValue N0  = Narrow->getOperand(0);
22578   SDValue N1  = Narrow->getOperand(1);
22579   SDLoc DL(Narrow);
22580
22581   // The Left side has to be a trunc.
22582   if (N0.getOpcode() != ISD::TRUNCATE)
22583     return SDValue();
22584
22585   // The type of the truncated inputs.
22586   EVT WideVT = N0->getOperand(0)->getValueType(0);
22587   if (WideVT != VT)
22588     return SDValue();
22589
22590   // The right side has to be a 'trunc' or a constant vector.
22591   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22592   ConstantSDNode *RHSConstSplat = nullptr;
22593   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22594     RHSConstSplat = RHSBV->getConstantSplatNode();
22595   if (!RHSTrunc && !RHSConstSplat)
22596     return SDValue();
22597
22598   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22599
22600   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22601     return SDValue();
22602
22603   // Set N0 and N1 to hold the inputs to the new wide operation.
22604   N0 = N0->getOperand(0);
22605   if (RHSConstSplat) {
22606     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22607                      SDValue(RHSConstSplat, 0));
22608     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22609     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22610   } else if (RHSTrunc) {
22611     N1 = N1->getOperand(0);
22612   }
22613
22614   // Generate the wide operation.
22615   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22616   unsigned Opcode = N->getOpcode();
22617   switch (Opcode) {
22618   case ISD::ANY_EXTEND:
22619     return Op;
22620   case ISD::ZERO_EXTEND: {
22621     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22622     APInt Mask = APInt::getAllOnesValue(InBits);
22623     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22624     return DAG.getNode(ISD::AND, DL, VT,
22625                        Op, DAG.getConstant(Mask, DL, VT));
22626   }
22627   case ISD::SIGN_EXTEND:
22628     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22629                        Op, DAG.getValueType(NarrowVT));
22630   default:
22631     llvm_unreachable("Unexpected opcode");
22632   }
22633 }
22634
22635 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22636                                  TargetLowering::DAGCombinerInfo &DCI,
22637                                  const X86Subtarget *Subtarget) {
22638   SDValue N0 = N->getOperand(0);
22639   SDValue N1 = N->getOperand(1);
22640   SDLoc DL(N);
22641
22642   // A vector zext_in_reg may be represented as a shuffle,
22643   // feeding into a bitcast (this represents anyext) feeding into
22644   // an and with a mask.
22645   // We'd like to try to combine that into a shuffle with zero
22646   // plus a bitcast, removing the and.
22647   if (N0.getOpcode() != ISD::BITCAST ||
22648       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22649     return SDValue();
22650
22651   // The other side of the AND should be a splat of 2^C, where C
22652   // is the number of bits in the source type.
22653   if (N1.getOpcode() == ISD::BITCAST)
22654     N1 = N1.getOperand(0);
22655   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22656     return SDValue();
22657   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22658
22659   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22660   EVT SrcType = Shuffle->getValueType(0);
22661
22662   // We expect a single-source shuffle
22663   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22664     return SDValue();
22665
22666   unsigned SrcSize = SrcType.getScalarSizeInBits();
22667
22668   APInt SplatValue, SplatUndef;
22669   unsigned SplatBitSize;
22670   bool HasAnyUndefs;
22671   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22672                                 SplatBitSize, HasAnyUndefs))
22673     return SDValue();
22674
22675   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22676   // Make sure the splat matches the mask we expect
22677   if (SplatBitSize > ResSize ||
22678       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22679     return SDValue();
22680
22681   // Make sure the input and output size make sense
22682   if (SrcSize >= ResSize || ResSize % SrcSize)
22683     return SDValue();
22684
22685   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22686   // The number of u's between each two values depends on the ratio between
22687   // the source and dest type.
22688   unsigned ZextRatio = ResSize / SrcSize;
22689   bool IsZext = true;
22690   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22691     if (i % ZextRatio) {
22692       if (Shuffle->getMaskElt(i) > 0) {
22693         // Expected undef
22694         IsZext = false;
22695         break;
22696       }
22697     } else {
22698       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22699         // Expected element number
22700         IsZext = false;
22701         break;
22702       }
22703     }
22704   }
22705
22706   if (!IsZext)
22707     return SDValue();
22708
22709   // Ok, perform the transformation - replace the shuffle with
22710   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22711   // (instead of undef) where the k elements come from the zero vector.
22712   SmallVector<int, 8> Mask;
22713   unsigned NumElems = SrcType.getVectorNumElements();
22714   for (unsigned i = 0; i < NumElems; ++i)
22715     if (i % ZextRatio)
22716       Mask.push_back(NumElems);
22717     else
22718       Mask.push_back(i / ZextRatio);
22719
22720   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22721     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22722   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22723 }
22724
22725 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22726                                  TargetLowering::DAGCombinerInfo &DCI,
22727                                  const X86Subtarget *Subtarget) {
22728   if (DCI.isBeforeLegalizeOps())
22729     return SDValue();
22730
22731   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22732     return Zext;
22733
22734   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22735     return R;
22736
22737   EVT VT = N->getValueType(0);
22738   SDValue N0 = N->getOperand(0);
22739   SDValue N1 = N->getOperand(1);
22740   SDLoc DL(N);
22741
22742   // Create BEXTR instructions
22743   // BEXTR is ((X >> imm) & (2**size-1))
22744   if (VT == MVT::i32 || VT == MVT::i64) {
22745     // Check for BEXTR.
22746     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22747         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22748       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22749       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22750       if (MaskNode && ShiftNode) {
22751         uint64_t Mask = MaskNode->getZExtValue();
22752         uint64_t Shift = ShiftNode->getZExtValue();
22753         if (isMask_64(Mask)) {
22754           uint64_t MaskSize = countPopulation(Mask);
22755           if (Shift + MaskSize <= VT.getSizeInBits())
22756             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22757                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22758                                                VT));
22759         }
22760       }
22761     } // BEXTR
22762
22763     return SDValue();
22764   }
22765
22766   // Want to form ANDNP nodes:
22767   // 1) In the hopes of then easily combining them with OR and AND nodes
22768   //    to form PBLEND/PSIGN.
22769   // 2) To match ANDN packed intrinsics
22770   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22771     return SDValue();
22772
22773   // Check LHS for vnot
22774   if (N0.getOpcode() == ISD::XOR &&
22775       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22776       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22777     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22778
22779   // Check RHS for vnot
22780   if (N1.getOpcode() == ISD::XOR &&
22781       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22782       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22783     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22784
22785   return SDValue();
22786 }
22787
22788 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22789                                 TargetLowering::DAGCombinerInfo &DCI,
22790                                 const X86Subtarget *Subtarget) {
22791   if (DCI.isBeforeLegalizeOps())
22792     return SDValue();
22793
22794   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22795   if (R.getNode())
22796     return R;
22797
22798   SDValue N0 = N->getOperand(0);
22799   SDValue N1 = N->getOperand(1);
22800   EVT VT = N->getValueType(0);
22801
22802   // look for psign/blend
22803   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22804     if (!Subtarget->hasSSSE3() ||
22805         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22806       return SDValue();
22807
22808     // Canonicalize pandn to RHS
22809     if (N0.getOpcode() == X86ISD::ANDNP)
22810       std::swap(N0, N1);
22811     // or (and (m, y), (pandn m, x))
22812     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22813       SDValue Mask = N1.getOperand(0);
22814       SDValue X    = N1.getOperand(1);
22815       SDValue Y;
22816       if (N0.getOperand(0) == Mask)
22817         Y = N0.getOperand(1);
22818       if (N0.getOperand(1) == Mask)
22819         Y = N0.getOperand(0);
22820
22821       // Check to see if the mask appeared in both the AND and ANDNP and
22822       if (!Y.getNode())
22823         return SDValue();
22824
22825       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22826       // Look through mask bitcast.
22827       if (Mask.getOpcode() == ISD::BITCAST)
22828         Mask = Mask.getOperand(0);
22829       if (X.getOpcode() == ISD::BITCAST)
22830         X = X.getOperand(0);
22831       if (Y.getOpcode() == ISD::BITCAST)
22832         Y = Y.getOperand(0);
22833
22834       EVT MaskVT = Mask.getValueType();
22835
22836       // Validate that the Mask operand is a vector sra node.
22837       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22838       // there is no psrai.b
22839       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22840       unsigned SraAmt = ~0;
22841       if (Mask.getOpcode() == ISD::SRA) {
22842         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22843           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22844             SraAmt = AmtConst->getZExtValue();
22845       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22846         SDValue SraC = Mask.getOperand(1);
22847         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22848       }
22849       if ((SraAmt + 1) != EltBits)
22850         return SDValue();
22851
22852       SDLoc DL(N);
22853
22854       // Now we know we at least have a plendvb with the mask val.  See if
22855       // we can form a psignb/w/d.
22856       // psign = x.type == y.type == mask.type && y = sub(0, x);
22857       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22858           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22859           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22860         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22861                "Unsupported VT for PSIGN");
22862         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22863         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22864       }
22865       // PBLENDVB only available on SSE 4.1
22866       if (!Subtarget->hasSSE41())
22867         return SDValue();
22868
22869       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22870
22871       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22872       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22873       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22874       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22875       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22876     }
22877   }
22878
22879   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22880     return SDValue();
22881
22882   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22883   MachineFunction &MF = DAG.getMachineFunction();
22884   bool OptForSize =
22885       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22886
22887   // SHLD/SHRD instructions have lower register pressure, but on some
22888   // platforms they have higher latency than the equivalent
22889   // series of shifts/or that would otherwise be generated.
22890   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22891   // have higher latencies and we are not optimizing for size.
22892   if (!OptForSize && Subtarget->isSHLDSlow())
22893     return SDValue();
22894
22895   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22896     std::swap(N0, N1);
22897   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22898     return SDValue();
22899   if (!N0.hasOneUse() || !N1.hasOneUse())
22900     return SDValue();
22901
22902   SDValue ShAmt0 = N0.getOperand(1);
22903   if (ShAmt0.getValueType() != MVT::i8)
22904     return SDValue();
22905   SDValue ShAmt1 = N1.getOperand(1);
22906   if (ShAmt1.getValueType() != MVT::i8)
22907     return SDValue();
22908   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22909     ShAmt0 = ShAmt0.getOperand(0);
22910   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22911     ShAmt1 = ShAmt1.getOperand(0);
22912
22913   SDLoc DL(N);
22914   unsigned Opc = X86ISD::SHLD;
22915   SDValue Op0 = N0.getOperand(0);
22916   SDValue Op1 = N1.getOperand(0);
22917   if (ShAmt0.getOpcode() == ISD::SUB) {
22918     Opc = X86ISD::SHRD;
22919     std::swap(Op0, Op1);
22920     std::swap(ShAmt0, ShAmt1);
22921   }
22922
22923   unsigned Bits = VT.getSizeInBits();
22924   if (ShAmt1.getOpcode() == ISD::SUB) {
22925     SDValue Sum = ShAmt1.getOperand(0);
22926     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22927       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22928       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22929         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22930       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22931         return DAG.getNode(Opc, DL, VT,
22932                            Op0, Op1,
22933                            DAG.getNode(ISD::TRUNCATE, DL,
22934                                        MVT::i8, ShAmt0));
22935     }
22936   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22937     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22938     if (ShAmt0C &&
22939         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22940       return DAG.getNode(Opc, DL, VT,
22941                          N0.getOperand(0), N1.getOperand(0),
22942                          DAG.getNode(ISD::TRUNCATE, DL,
22943                                        MVT::i8, ShAmt0));
22944   }
22945
22946   return SDValue();
22947 }
22948
22949 // Generate NEG and CMOV for integer abs.
22950 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22951   EVT VT = N->getValueType(0);
22952
22953   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22954   // 8-bit integer abs to NEG and CMOV.
22955   if (VT.isInteger() && VT.getSizeInBits() == 8)
22956     return SDValue();
22957
22958   SDValue N0 = N->getOperand(0);
22959   SDValue N1 = N->getOperand(1);
22960   SDLoc DL(N);
22961
22962   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22963   // and change it to SUB and CMOV.
22964   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22965       N0.getOpcode() == ISD::ADD &&
22966       N0.getOperand(1) == N1 &&
22967       N1.getOpcode() == ISD::SRA &&
22968       N1.getOperand(0) == N0.getOperand(0))
22969     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22970       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22971         // Generate SUB & CMOV.
22972         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22973                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
22974
22975         SDValue Ops[] = { N0.getOperand(0), Neg,
22976                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22977                           SDValue(Neg.getNode(), 1) };
22978         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22979       }
22980   return SDValue();
22981 }
22982
22983 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22984 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22985                                  TargetLowering::DAGCombinerInfo &DCI,
22986                                  const X86Subtarget *Subtarget) {
22987   if (DCI.isBeforeLegalizeOps())
22988     return SDValue();
22989
22990   if (Subtarget->hasCMov()) {
22991     SDValue RV = performIntegerAbsCombine(N, DAG);
22992     if (RV.getNode())
22993       return RV;
22994   }
22995
22996   return SDValue();
22997 }
22998
22999 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23000 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23001                                   TargetLowering::DAGCombinerInfo &DCI,
23002                                   const X86Subtarget *Subtarget) {
23003   LoadSDNode *Ld = cast<LoadSDNode>(N);
23004   EVT RegVT = Ld->getValueType(0);
23005   EVT MemVT = Ld->getMemoryVT();
23006   SDLoc dl(Ld);
23007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23008
23009   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23010   // into two 16-byte operations.
23011   ISD::LoadExtType Ext = Ld->getExtensionType();
23012   unsigned Alignment = Ld->getAlignment();
23013   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23014   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23015       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23016     unsigned NumElems = RegVT.getVectorNumElements();
23017     if (NumElems < 2)
23018       return SDValue();
23019
23020     SDValue Ptr = Ld->getBasePtr();
23021     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
23022
23023     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23024                                   NumElems/2);
23025     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23026                                 Ld->getPointerInfo(), Ld->isVolatile(),
23027                                 Ld->isNonTemporal(), Ld->isInvariant(),
23028                                 Alignment);
23029     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23030     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23031                                 Ld->getPointerInfo(), Ld->isVolatile(),
23032                                 Ld->isNonTemporal(), Ld->isInvariant(),
23033                                 std::min(16U, Alignment));
23034     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23035                              Load1.getValue(1),
23036                              Load2.getValue(1));
23037
23038     SDValue NewVec = DAG.getUNDEF(RegVT);
23039     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23040     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23041     return DCI.CombineTo(N, NewVec, TF, true);
23042   }
23043
23044   return SDValue();
23045 }
23046
23047 /// PerformMLOADCombine - Resolve extending loads
23048 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23049                                    TargetLowering::DAGCombinerInfo &DCI,
23050                                    const X86Subtarget *Subtarget) {
23051   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23052   if (Mld->getExtensionType() != ISD::SEXTLOAD)
23053     return SDValue();
23054
23055   EVT VT = Mld->getValueType(0);
23056   unsigned NumElems = VT.getVectorNumElements();
23057   EVT LdVT = Mld->getMemoryVT();
23058   SDLoc dl(Mld);
23059
23060   assert(LdVT != VT && "Cannot extend to the same type");
23061   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23062   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23063   // From, To sizes and ElemCount must be pow of two
23064   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23065     "Unexpected size for extending masked load");
23066
23067   unsigned SizeRatio  = ToSz / FromSz;
23068   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23069
23070   // Create a type on which we perform the shuffle
23071   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23072           LdVT.getScalarType(), NumElems*SizeRatio);
23073   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23074
23075   // Convert Src0 value
23076   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
23077   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23078     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23079     for (unsigned i = 0; i != NumElems; ++i)
23080       ShuffleVec[i] = i * SizeRatio;
23081
23082     // Can't shuffle using an illegal type.
23083     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23084             && "WideVecVT should be legal");
23085     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23086                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23087   }
23088   // Prepare the new mask
23089   SDValue NewMask;
23090   SDValue Mask = Mld->getMask();
23091   if (Mask.getValueType() == VT) {
23092     // Mask and original value have the same type
23093     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23094     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23095     for (unsigned i = 0; i != NumElems; ++i)
23096       ShuffleVec[i] = i * SizeRatio;
23097     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23098       ShuffleVec[i] = NumElems*SizeRatio;
23099     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23100                                    DAG.getConstant(0, dl, WideVecVT),
23101                                    &ShuffleVec[0]);
23102   }
23103   else {
23104     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23105     unsigned WidenNumElts = NumElems*SizeRatio;
23106     unsigned MaskNumElts = VT.getVectorNumElements();
23107     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23108                                      WidenNumElts);
23109
23110     unsigned NumConcat = WidenNumElts / MaskNumElts;
23111     SmallVector<SDValue, 16> Ops(NumConcat);
23112     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23113     Ops[0] = Mask;
23114     for (unsigned i = 1; i != NumConcat; ++i)
23115       Ops[i] = ZeroVal;
23116
23117     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23118   }
23119
23120   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23121                                      Mld->getBasePtr(), NewMask, WideSrc0,
23122                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23123                                      ISD::NON_EXTLOAD);
23124   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23125   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23126
23127 }
23128 /// PerformMSTORECombine - Resolve truncating stores
23129 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23130                                     const X86Subtarget *Subtarget) {
23131   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23132   if (!Mst->isTruncatingStore())
23133     return SDValue();
23134
23135   EVT VT = Mst->getValue().getValueType();
23136   unsigned NumElems = VT.getVectorNumElements();
23137   EVT StVT = Mst->getMemoryVT();
23138   SDLoc dl(Mst);
23139
23140   assert(StVT != VT && "Cannot truncate to the same type");
23141   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23142   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23143
23144   // From, To sizes and ElemCount must be pow of two
23145   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23146     "Unexpected size for truncating masked store");
23147   // We are going to use the original vector elt for storing.
23148   // Accumulated smaller vector elements must be a multiple of the store size.
23149   assert (((NumElems * FromSz) % ToSz) == 0 &&
23150           "Unexpected ratio for truncating masked store");
23151
23152   unsigned SizeRatio  = FromSz / ToSz;
23153   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23154
23155   // Create a type on which we perform the shuffle
23156   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23157           StVT.getScalarType(), NumElems*SizeRatio);
23158
23159   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23160
23161   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23162   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23163   for (unsigned i = 0; i != NumElems; ++i)
23164     ShuffleVec[i] = i * SizeRatio;
23165
23166   // Can't shuffle using an illegal type.
23167   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23168           && "WideVecVT should be legal");
23169
23170   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23171                                         DAG.getUNDEF(WideVecVT),
23172                                         &ShuffleVec[0]);
23173
23174   SDValue NewMask;
23175   SDValue Mask = Mst->getMask();
23176   if (Mask.getValueType() == VT) {
23177     // Mask and original value have the same type
23178     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23179     for (unsigned i = 0; i != NumElems; ++i)
23180       ShuffleVec[i] = i * SizeRatio;
23181     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23182       ShuffleVec[i] = NumElems*SizeRatio;
23183     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23184                                    DAG.getConstant(0, dl, WideVecVT),
23185                                    &ShuffleVec[0]);
23186   }
23187   else {
23188     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23189     unsigned WidenNumElts = NumElems*SizeRatio;
23190     unsigned MaskNumElts = VT.getVectorNumElements();
23191     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23192                                      WidenNumElts);
23193
23194     unsigned NumConcat = WidenNumElts / MaskNumElts;
23195     SmallVector<SDValue, 16> Ops(NumConcat);
23196     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23197     Ops[0] = Mask;
23198     for (unsigned i = 1; i != NumConcat; ++i)
23199       Ops[i] = ZeroVal;
23200
23201     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23202   }
23203
23204   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23205                             NewMask, StVT, Mst->getMemOperand(), false);
23206 }
23207 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23208 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23209                                    const X86Subtarget *Subtarget) {
23210   StoreSDNode *St = cast<StoreSDNode>(N);
23211   EVT VT = St->getValue().getValueType();
23212   EVT StVT = St->getMemoryVT();
23213   SDLoc dl(St);
23214   SDValue StoredVal = St->getOperand(1);
23215   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23216
23217   // If we are saving a concatenation of two XMM registers and 32-byte stores
23218   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23219   unsigned Alignment = St->getAlignment();
23220   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23221   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23222       StVT == VT && !IsAligned) {
23223     unsigned NumElems = VT.getVectorNumElements();
23224     if (NumElems < 2)
23225       return SDValue();
23226
23227     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23228     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23229
23230     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23231     SDValue Ptr0 = St->getBasePtr();
23232     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23233
23234     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23235                                 St->getPointerInfo(), St->isVolatile(),
23236                                 St->isNonTemporal(), Alignment);
23237     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23238                                 St->getPointerInfo(), St->isVolatile(),
23239                                 St->isNonTemporal(),
23240                                 std::min(16U, Alignment));
23241     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23242   }
23243
23244   // Optimize trunc store (of multiple scalars) to shuffle and store.
23245   // First, pack all of the elements in one place. Next, store to memory
23246   // in fewer chunks.
23247   if (St->isTruncatingStore() && VT.isVector()) {
23248     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23249     unsigned NumElems = VT.getVectorNumElements();
23250     assert(StVT != VT && "Cannot truncate to the same type");
23251     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23252     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23253
23254     // From, To sizes and ElemCount must be pow of two
23255     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23256     // We are going to use the original vector elt for storing.
23257     // Accumulated smaller vector elements must be a multiple of the store size.
23258     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23259
23260     unsigned SizeRatio  = FromSz / ToSz;
23261
23262     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23263
23264     // Create a type on which we perform the shuffle
23265     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23266             StVT.getScalarType(), NumElems*SizeRatio);
23267
23268     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23269
23270     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23271     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23272     for (unsigned i = 0; i != NumElems; ++i)
23273       ShuffleVec[i] = i * SizeRatio;
23274
23275     // Can't shuffle using an illegal type.
23276     if (!TLI.isTypeLegal(WideVecVT))
23277       return SDValue();
23278
23279     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23280                                          DAG.getUNDEF(WideVecVT),
23281                                          &ShuffleVec[0]);
23282     // At this point all of the data is stored at the bottom of the
23283     // register. We now need to save it to mem.
23284
23285     // Find the largest store unit
23286     MVT StoreType = MVT::i8;
23287     for (MVT Tp : MVT::integer_valuetypes()) {
23288       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23289         StoreType = Tp;
23290     }
23291
23292     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23293     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23294         (64 <= NumElems * ToSz))
23295       StoreType = MVT::f64;
23296
23297     // Bitcast the original vector into a vector of store-size units
23298     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23299             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23300     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23301     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23302     SmallVector<SDValue, 8> Chains;
23303     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23304                                         TLI.getPointerTy());
23305     SDValue Ptr = St->getBasePtr();
23306
23307     // Perform one or more big stores into memory.
23308     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23309       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23310                                    StoreType, ShuffWide,
23311                                    DAG.getIntPtrConstant(i, dl));
23312       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23313                                 St->getPointerInfo(), St->isVolatile(),
23314                                 St->isNonTemporal(), St->getAlignment());
23315       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23316       Chains.push_back(Ch);
23317     }
23318
23319     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23320   }
23321
23322   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23323   // the FP state in cases where an emms may be missing.
23324   // A preferable solution to the general problem is to figure out the right
23325   // places to insert EMMS.  This qualifies as a quick hack.
23326
23327   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23328   if (VT.getSizeInBits() != 64)
23329     return SDValue();
23330
23331   const Function *F = DAG.getMachineFunction().getFunction();
23332   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23333   bool F64IsLegal =
23334       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23335   if ((VT.isVector() ||
23336        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23337       isa<LoadSDNode>(St->getValue()) &&
23338       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23339       St->getChain().hasOneUse() && !St->isVolatile()) {
23340     SDNode* LdVal = St->getValue().getNode();
23341     LoadSDNode *Ld = nullptr;
23342     int TokenFactorIndex = -1;
23343     SmallVector<SDValue, 8> Ops;
23344     SDNode* ChainVal = St->getChain().getNode();
23345     // Must be a store of a load.  We currently handle two cases:  the load
23346     // is a direct child, and it's under an intervening TokenFactor.  It is
23347     // possible to dig deeper under nested TokenFactors.
23348     if (ChainVal == LdVal)
23349       Ld = cast<LoadSDNode>(St->getChain());
23350     else if (St->getValue().hasOneUse() &&
23351              ChainVal->getOpcode() == ISD::TokenFactor) {
23352       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23353         if (ChainVal->getOperand(i).getNode() == LdVal) {
23354           TokenFactorIndex = i;
23355           Ld = cast<LoadSDNode>(St->getValue());
23356         } else
23357           Ops.push_back(ChainVal->getOperand(i));
23358       }
23359     }
23360
23361     if (!Ld || !ISD::isNormalLoad(Ld))
23362       return SDValue();
23363
23364     // If this is not the MMX case, i.e. we are just turning i64 load/store
23365     // into f64 load/store, avoid the transformation if there are multiple
23366     // uses of the loaded value.
23367     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23368       return SDValue();
23369
23370     SDLoc LdDL(Ld);
23371     SDLoc StDL(N);
23372     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23373     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23374     // pair instead.
23375     if (Subtarget->is64Bit() || F64IsLegal) {
23376       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23377       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23378                                   Ld->getPointerInfo(), Ld->isVolatile(),
23379                                   Ld->isNonTemporal(), Ld->isInvariant(),
23380                                   Ld->getAlignment());
23381       SDValue NewChain = NewLd.getValue(1);
23382       if (TokenFactorIndex != -1) {
23383         Ops.push_back(NewChain);
23384         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23385       }
23386       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23387                           St->getPointerInfo(),
23388                           St->isVolatile(), St->isNonTemporal(),
23389                           St->getAlignment());
23390     }
23391
23392     // Otherwise, lower to two pairs of 32-bit loads / stores.
23393     SDValue LoAddr = Ld->getBasePtr();
23394     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23395                                  DAG.getConstant(4, LdDL, MVT::i32));
23396
23397     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23398                                Ld->getPointerInfo(),
23399                                Ld->isVolatile(), Ld->isNonTemporal(),
23400                                Ld->isInvariant(), Ld->getAlignment());
23401     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23402                                Ld->getPointerInfo().getWithOffset(4),
23403                                Ld->isVolatile(), Ld->isNonTemporal(),
23404                                Ld->isInvariant(),
23405                                MinAlign(Ld->getAlignment(), 4));
23406
23407     SDValue NewChain = LoLd.getValue(1);
23408     if (TokenFactorIndex != -1) {
23409       Ops.push_back(LoLd);
23410       Ops.push_back(HiLd);
23411       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23412     }
23413
23414     LoAddr = St->getBasePtr();
23415     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23416                          DAG.getConstant(4, StDL, MVT::i32));
23417
23418     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23419                                 St->getPointerInfo(),
23420                                 St->isVolatile(), St->isNonTemporal(),
23421                                 St->getAlignment());
23422     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23423                                 St->getPointerInfo().getWithOffset(4),
23424                                 St->isVolatile(),
23425                                 St->isNonTemporal(),
23426                                 MinAlign(St->getAlignment(), 4));
23427     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23428   }
23429
23430   // This is similar to the above case, but here we handle a scalar 64-bit
23431   // integer store that is extracted from a vector on a 32-bit target.
23432   // If we have SSE2, then we can treat it like a floating-point double
23433   // to get past legalization. The execution dependencies fixup pass will
23434   // choose the optimal machine instruction for the store if this really is
23435   // an integer or v2f32 rather than an f64.
23436   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23437       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23438     SDValue OldExtract = St->getOperand(1);
23439     SDValue ExtOp0 = OldExtract.getOperand(0);
23440     unsigned VecSize = ExtOp0.getValueSizeInBits();
23441     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23442     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23443     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23444                                      BitCast, OldExtract.getOperand(1));
23445     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23446                         St->getPointerInfo(), St->isVolatile(),
23447                         St->isNonTemporal(), St->getAlignment());
23448   }
23449
23450   return SDValue();
23451 }
23452
23453 /// Return 'true' if this vector operation is "horizontal"
23454 /// and return the operands for the horizontal operation in LHS and RHS.  A
23455 /// horizontal operation performs the binary operation on successive elements
23456 /// of its first operand, then on successive elements of its second operand,
23457 /// returning the resulting values in a vector.  For example, if
23458 ///   A = < float a0, float a1, float a2, float a3 >
23459 /// and
23460 ///   B = < float b0, float b1, float b2, float b3 >
23461 /// then the result of doing a horizontal operation on A and B is
23462 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23463 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23464 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23465 /// set to A, RHS to B, and the routine returns 'true'.
23466 /// Note that the binary operation should have the property that if one of the
23467 /// operands is UNDEF then the result is UNDEF.
23468 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23469   // Look for the following pattern: if
23470   //   A = < float a0, float a1, float a2, float a3 >
23471   //   B = < float b0, float b1, float b2, float b3 >
23472   // and
23473   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23474   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23475   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23476   // which is A horizontal-op B.
23477
23478   // At least one of the operands should be a vector shuffle.
23479   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23480       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23481     return false;
23482
23483   MVT VT = LHS.getSimpleValueType();
23484
23485   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23486          "Unsupported vector type for horizontal add/sub");
23487
23488   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23489   // operate independently on 128-bit lanes.
23490   unsigned NumElts = VT.getVectorNumElements();
23491   unsigned NumLanes = VT.getSizeInBits()/128;
23492   unsigned NumLaneElts = NumElts / NumLanes;
23493   assert((NumLaneElts % 2 == 0) &&
23494          "Vector type should have an even number of elements in each lane");
23495   unsigned HalfLaneElts = NumLaneElts/2;
23496
23497   // View LHS in the form
23498   //   LHS = VECTOR_SHUFFLE A, B, LMask
23499   // If LHS is not a shuffle then pretend it is the shuffle
23500   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23501   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23502   // type VT.
23503   SDValue A, B;
23504   SmallVector<int, 16> LMask(NumElts);
23505   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23506     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23507       A = LHS.getOperand(0);
23508     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23509       B = LHS.getOperand(1);
23510     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23511     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23512   } else {
23513     if (LHS.getOpcode() != ISD::UNDEF)
23514       A = LHS;
23515     for (unsigned i = 0; i != NumElts; ++i)
23516       LMask[i] = i;
23517   }
23518
23519   // Likewise, view RHS in the form
23520   //   RHS = VECTOR_SHUFFLE C, D, RMask
23521   SDValue C, D;
23522   SmallVector<int, 16> RMask(NumElts);
23523   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23524     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23525       C = RHS.getOperand(0);
23526     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23527       D = RHS.getOperand(1);
23528     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23529     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23530   } else {
23531     if (RHS.getOpcode() != ISD::UNDEF)
23532       C = RHS;
23533     for (unsigned i = 0; i != NumElts; ++i)
23534       RMask[i] = i;
23535   }
23536
23537   // Check that the shuffles are both shuffling the same vectors.
23538   if (!(A == C && B == D) && !(A == D && B == C))
23539     return false;
23540
23541   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23542   if (!A.getNode() && !B.getNode())
23543     return false;
23544
23545   // If A and B occur in reverse order in RHS, then "swap" them (which means
23546   // rewriting the mask).
23547   if (A != C)
23548     ShuffleVectorSDNode::commuteMask(RMask);
23549
23550   // At this point LHS and RHS are equivalent to
23551   //   LHS = VECTOR_SHUFFLE A, B, LMask
23552   //   RHS = VECTOR_SHUFFLE A, B, RMask
23553   // Check that the masks correspond to performing a horizontal operation.
23554   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23555     for (unsigned i = 0; i != NumLaneElts; ++i) {
23556       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23557
23558       // Ignore any UNDEF components.
23559       if (LIdx < 0 || RIdx < 0 ||
23560           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23561           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23562         continue;
23563
23564       // Check that successive elements are being operated on.  If not, this is
23565       // not a horizontal operation.
23566       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23567       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23568       if (!(LIdx == Index && RIdx == Index + 1) &&
23569           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23570         return false;
23571     }
23572   }
23573
23574   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23575   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23576   return true;
23577 }
23578
23579 /// Do target-specific dag combines on floating point adds.
23580 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23581                                   const X86Subtarget *Subtarget) {
23582   EVT VT = N->getValueType(0);
23583   SDValue LHS = N->getOperand(0);
23584   SDValue RHS = N->getOperand(1);
23585
23586   // Try to synthesize horizontal adds from adds of shuffles.
23587   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23588        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23589       isHorizontalBinOp(LHS, RHS, true))
23590     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23591   return SDValue();
23592 }
23593
23594 /// Do target-specific dag combines on floating point subs.
23595 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23596                                   const X86Subtarget *Subtarget) {
23597   EVT VT = N->getValueType(0);
23598   SDValue LHS = N->getOperand(0);
23599   SDValue RHS = N->getOperand(1);
23600
23601   // Try to synthesize horizontal subs from subs of shuffles.
23602   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23603        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23604       isHorizontalBinOp(LHS, RHS, false))
23605     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23606   return SDValue();
23607 }
23608
23609 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23610 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23611   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23612
23613   // F[X]OR(0.0, x) -> x
23614   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23615     if (C->getValueAPF().isPosZero())
23616       return N->getOperand(1);
23617
23618   // F[X]OR(x, 0.0) -> x
23619   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23620     if (C->getValueAPF().isPosZero())
23621       return N->getOperand(0);
23622   return SDValue();
23623 }
23624
23625 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23626 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23627   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23628
23629   // Only perform optimizations if UnsafeMath is used.
23630   if (!DAG.getTarget().Options.UnsafeFPMath)
23631     return SDValue();
23632
23633   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23634   // into FMINC and FMAXC, which are Commutative operations.
23635   unsigned NewOp = 0;
23636   switch (N->getOpcode()) {
23637     default: llvm_unreachable("unknown opcode");
23638     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23639     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23640   }
23641
23642   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23643                      N->getOperand(0), N->getOperand(1));
23644 }
23645
23646 /// Do target-specific dag combines on X86ISD::FAND nodes.
23647 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23648   // FAND(0.0, x) -> 0.0
23649   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23650     if (C->getValueAPF().isPosZero())
23651       return N->getOperand(0);
23652
23653   // FAND(x, 0.0) -> 0.0
23654   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23655     if (C->getValueAPF().isPosZero())
23656       return N->getOperand(1);
23657
23658   return SDValue();
23659 }
23660
23661 /// Do target-specific dag combines on X86ISD::FANDN nodes
23662 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23663   // FANDN(0.0, x) -> x
23664   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23665     if (C->getValueAPF().isPosZero())
23666       return N->getOperand(1);
23667
23668   // FANDN(x, 0.0) -> 0.0
23669   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23670     if (C->getValueAPF().isPosZero())
23671       return N->getOperand(1);
23672
23673   return SDValue();
23674 }
23675
23676 static SDValue PerformBTCombine(SDNode *N,
23677                                 SelectionDAG &DAG,
23678                                 TargetLowering::DAGCombinerInfo &DCI) {
23679   // BT ignores high bits in the bit index operand.
23680   SDValue Op1 = N->getOperand(1);
23681   if (Op1.hasOneUse()) {
23682     unsigned BitWidth = Op1.getValueSizeInBits();
23683     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23684     APInt KnownZero, KnownOne;
23685     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23686                                           !DCI.isBeforeLegalizeOps());
23687     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23688     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23689         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23690       DCI.CommitTargetLoweringOpt(TLO);
23691   }
23692   return SDValue();
23693 }
23694
23695 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23696   SDValue Op = N->getOperand(0);
23697   if (Op.getOpcode() == ISD::BITCAST)
23698     Op = Op.getOperand(0);
23699   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23700   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23701       VT.getVectorElementType().getSizeInBits() ==
23702       OpVT.getVectorElementType().getSizeInBits()) {
23703     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23704   }
23705   return SDValue();
23706 }
23707
23708 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23709                                                const X86Subtarget *Subtarget) {
23710   EVT VT = N->getValueType(0);
23711   if (!VT.isVector())
23712     return SDValue();
23713
23714   SDValue N0 = N->getOperand(0);
23715   SDValue N1 = N->getOperand(1);
23716   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23717   SDLoc dl(N);
23718
23719   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23720   // both SSE and AVX2 since there is no sign-extended shift right
23721   // operation on a vector with 64-bit elements.
23722   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23723   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23724   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23725       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23726     SDValue N00 = N0.getOperand(0);
23727
23728     // EXTLOAD has a better solution on AVX2,
23729     // it may be replaced with X86ISD::VSEXT node.
23730     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23731       if (!ISD::isNormalLoad(N00.getNode()))
23732         return SDValue();
23733
23734     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23735         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23736                                   N00, N1);
23737       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23738     }
23739   }
23740   return SDValue();
23741 }
23742
23743 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23744                                   TargetLowering::DAGCombinerInfo &DCI,
23745                                   const X86Subtarget *Subtarget) {
23746   SDValue N0 = N->getOperand(0);
23747   EVT VT = N->getValueType(0);
23748   EVT SVT = VT.getScalarType();
23749   EVT InVT = N0->getValueType(0);
23750   EVT InSVT = InVT.getScalarType();
23751   SDLoc DL(N);
23752
23753   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23754   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23755   // This exposes the sext to the sdivrem lowering, so that it directly extends
23756   // from AH (which we otherwise need to do contortions to access).
23757   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23758       InVT == MVT::i8 && VT == MVT::i32) {
23759     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23760     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
23761                             N0.getOperand(0), N0.getOperand(1));
23762     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23763     return R.getValue(1);
23764   }
23765
23766   if (!DCI.isBeforeLegalizeOps()) {
23767     if (N0.getValueType() == MVT::i1) {
23768       SDValue Zero = DAG.getConstant(0, DL, VT);
23769       SDValue AllOnes =
23770         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
23771       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
23772     }
23773     return SDValue();
23774   }
23775
23776   if (VT.isVector()) {
23777     auto ExtendToVec128 = [&DAG](SDLoc DL, SDValue N) {
23778       EVT InVT = N->getValueType(0);
23779       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
23780                                    128 / InVT.getScalarSizeInBits());
23781       SmallVector<SDValue, 8> Opnds(128 / InVT.getSizeInBits(),
23782                                     DAG.getUNDEF(InVT));
23783       Opnds[0] = N;
23784       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
23785     };
23786
23787     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
23788     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
23789     if (VT.getSizeInBits() == 128 &&
23790         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23791         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23792       SDValue ExOp = ExtendToVec128(DL, N0);
23793       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
23794     }
23795
23796     // On pre-AVX2 targets, split into 128-bit nodes of
23797     // ISD::SIGN_EXTEND_VECTOR_INREG.
23798     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
23799         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23800         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23801       unsigned NumVecs = VT.getSizeInBits() / 128;
23802       unsigned NumSubElts = 128 / SVT.getSizeInBits();
23803       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
23804       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
23805
23806       SmallVector<SDValue, 8> Opnds;
23807       for (unsigned i = 0, Offset = 0; i != NumVecs;
23808            ++i, Offset += NumSubElts) {
23809         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
23810                                      DAG.getIntPtrConstant(Offset, DL));
23811         SrcVec = ExtendToVec128(DL, SrcVec);
23812         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
23813         Opnds.push_back(SrcVec);
23814       }
23815       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
23816     }
23817   }
23818
23819   if (!Subtarget->hasFp256())
23820     return SDValue();
23821
23822   if (VT.isVector() && VT.getSizeInBits() == 256) {
23823     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23824     if (R.getNode())
23825       return R;
23826   }
23827
23828   return SDValue();
23829 }
23830
23831 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23832                                  const X86Subtarget* Subtarget) {
23833   SDLoc dl(N);
23834   EVT VT = N->getValueType(0);
23835
23836   // Let legalize expand this if it isn't a legal type yet.
23837   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23838     return SDValue();
23839
23840   EVT ScalarVT = VT.getScalarType();
23841   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23842       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23843     return SDValue();
23844
23845   SDValue A = N->getOperand(0);
23846   SDValue B = N->getOperand(1);
23847   SDValue C = N->getOperand(2);
23848
23849   bool NegA = (A.getOpcode() == ISD::FNEG);
23850   bool NegB = (B.getOpcode() == ISD::FNEG);
23851   bool NegC = (C.getOpcode() == ISD::FNEG);
23852
23853   // Negative multiplication when NegA xor NegB
23854   bool NegMul = (NegA != NegB);
23855   if (NegA)
23856     A = A.getOperand(0);
23857   if (NegB)
23858     B = B.getOperand(0);
23859   if (NegC)
23860     C = C.getOperand(0);
23861
23862   unsigned Opcode;
23863   if (!NegMul)
23864     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23865   else
23866     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23867
23868   return DAG.getNode(Opcode, dl, VT, A, B, C);
23869 }
23870
23871 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23872                                   TargetLowering::DAGCombinerInfo &DCI,
23873                                   const X86Subtarget *Subtarget) {
23874   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23875   //           (and (i32 x86isd::setcc_carry), 1)
23876   // This eliminates the zext. This transformation is necessary because
23877   // ISD::SETCC is always legalized to i8.
23878   SDLoc dl(N);
23879   SDValue N0 = N->getOperand(0);
23880   EVT VT = N->getValueType(0);
23881
23882   if (N0.getOpcode() == ISD::AND &&
23883       N0.hasOneUse() &&
23884       N0.getOperand(0).hasOneUse()) {
23885     SDValue N00 = N0.getOperand(0);
23886     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23887       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23888       if (!C || C->getZExtValue() != 1)
23889         return SDValue();
23890       return DAG.getNode(ISD::AND, dl, VT,
23891                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23892                                      N00.getOperand(0), N00.getOperand(1)),
23893                          DAG.getConstant(1, dl, VT));
23894     }
23895   }
23896
23897   if (N0.getOpcode() == ISD::TRUNCATE &&
23898       N0.hasOneUse() &&
23899       N0.getOperand(0).hasOneUse()) {
23900     SDValue N00 = N0.getOperand(0);
23901     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23902       return DAG.getNode(ISD::AND, dl, VT,
23903                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23904                                      N00.getOperand(0), N00.getOperand(1)),
23905                          DAG.getConstant(1, dl, VT));
23906     }
23907   }
23908   if (VT.is256BitVector()) {
23909     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23910     if (R.getNode())
23911       return R;
23912   }
23913
23914   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23915   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23916   // This exposes the zext to the udivrem lowering, so that it directly extends
23917   // from AH (which we otherwise need to do contortions to access).
23918   if (N0.getOpcode() == ISD::UDIVREM &&
23919       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23920       (VT == MVT::i32 || VT == MVT::i64)) {
23921     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23922     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23923                             N0.getOperand(0), N0.getOperand(1));
23924     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23925     return R.getValue(1);
23926   }
23927
23928   return SDValue();
23929 }
23930
23931 // Optimize x == -y --> x+y == 0
23932 //          x != -y --> x+y != 0
23933 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23934                                       const X86Subtarget* Subtarget) {
23935   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23936   SDValue LHS = N->getOperand(0);
23937   SDValue RHS = N->getOperand(1);
23938   EVT VT = N->getValueType(0);
23939   SDLoc DL(N);
23940
23941   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23942     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23943       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23944         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23945                                    LHS.getOperand(1));
23946         return DAG.getSetCC(DL, N->getValueType(0), addV,
23947                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23948       }
23949   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23950     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23951       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23952         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23953                                    RHS.getOperand(1));
23954         return DAG.getSetCC(DL, N->getValueType(0), addV,
23955                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23956       }
23957
23958   if (VT.getScalarType() == MVT::i1 &&
23959       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23960     bool IsSEXT0 =
23961         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23962         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23963     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23964
23965     if (!IsSEXT0 || !IsVZero1) {
23966       // Swap the operands and update the condition code.
23967       std::swap(LHS, RHS);
23968       CC = ISD::getSetCCSwappedOperands(CC);
23969
23970       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23971                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23972       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23973     }
23974
23975     if (IsSEXT0 && IsVZero1) {
23976       assert(VT == LHS.getOperand(0).getValueType() &&
23977              "Uexpected operand type");
23978       if (CC == ISD::SETGT)
23979         return DAG.getConstant(0, DL, VT);
23980       if (CC == ISD::SETLE)
23981         return DAG.getConstant(1, DL, VT);
23982       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23983         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23984
23985       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23986              "Unexpected condition code!");
23987       return LHS.getOperand(0);
23988     }
23989   }
23990
23991   return SDValue();
23992 }
23993
23994 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23995                                          SelectionDAG &DAG) {
23996   SDLoc dl(Load);
23997   MVT VT = Load->getSimpleValueType(0);
23998   MVT EVT = VT.getVectorElementType();
23999   SDValue Addr = Load->getOperand(1);
24000   SDValue NewAddr = DAG.getNode(
24001       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24002       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24003                       Addr.getSimpleValueType()));
24004
24005   SDValue NewLoad =
24006       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24007                   DAG.getMachineFunction().getMachineMemOperand(
24008                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24009   return NewLoad;
24010 }
24011
24012 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24013                                       const X86Subtarget *Subtarget) {
24014   SDLoc dl(N);
24015   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24016   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24017          "X86insertps is only defined for v4x32");
24018
24019   SDValue Ld = N->getOperand(1);
24020   if (MayFoldLoad(Ld)) {
24021     // Extract the countS bits from the immediate so we can get the proper
24022     // address when narrowing the vector load to a specific element.
24023     // When the second source op is a memory address, insertps doesn't use
24024     // countS and just gets an f32 from that address.
24025     unsigned DestIndex =
24026         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24027
24028     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24029
24030     // Create this as a scalar to vector to match the instruction pattern.
24031     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24032     // countS bits are ignored when loading from memory on insertps, which
24033     // means we don't need to explicitly set them to 0.
24034     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24035                        LoadScalarToVector, N->getOperand(2));
24036   }
24037   return SDValue();
24038 }
24039
24040 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24041   SDValue V0 = N->getOperand(0);
24042   SDValue V1 = N->getOperand(1);
24043   SDLoc DL(N);
24044   EVT VT = N->getValueType(0);
24045
24046   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24047   // operands and changing the mask to 1. This saves us a bunch of
24048   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24049   // x86InstrInfo knows how to commute this back after instruction selection
24050   // if it would help register allocation.
24051
24052   // TODO: If optimizing for size or a processor that doesn't suffer from
24053   // partial register update stalls, this should be transformed into a MOVSD
24054   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24055
24056   if (VT == MVT::v2f64)
24057     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24058       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24059         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24060         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24061       }
24062
24063   return SDValue();
24064 }
24065
24066 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24067 // as "sbb reg,reg", since it can be extended without zext and produces
24068 // an all-ones bit which is more useful than 0/1 in some cases.
24069 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24070                                MVT VT) {
24071   if (VT == MVT::i8)
24072     return DAG.getNode(ISD::AND, DL, VT,
24073                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24074                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
24075                                    EFLAGS),
24076                        DAG.getConstant(1, DL, VT));
24077   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24078   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24079                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24080                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
24081                                  EFLAGS));
24082 }
24083
24084 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24085 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24086                                    TargetLowering::DAGCombinerInfo &DCI,
24087                                    const X86Subtarget *Subtarget) {
24088   SDLoc DL(N);
24089   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24090   SDValue EFLAGS = N->getOperand(1);
24091
24092   if (CC == X86::COND_A) {
24093     // Try to convert COND_A into COND_B in an attempt to facilitate
24094     // materializing "setb reg".
24095     //
24096     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24097     // cannot take an immediate as its first operand.
24098     //
24099     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24100         EFLAGS.getValueType().isInteger() &&
24101         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24102       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24103                                    EFLAGS.getNode()->getVTList(),
24104                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24105       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24106       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24107     }
24108   }
24109
24110   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24111   // a zext and produces an all-ones bit which is more useful than 0/1 in some
24112   // cases.
24113   if (CC == X86::COND_B)
24114     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24115
24116   SDValue Flags;
24117
24118   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24119   if (Flags.getNode()) {
24120     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24121     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24122   }
24123
24124   return SDValue();
24125 }
24126
24127 // Optimize branch condition evaluation.
24128 //
24129 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24130                                     TargetLowering::DAGCombinerInfo &DCI,
24131                                     const X86Subtarget *Subtarget) {
24132   SDLoc DL(N);
24133   SDValue Chain = N->getOperand(0);
24134   SDValue Dest = N->getOperand(1);
24135   SDValue EFLAGS = N->getOperand(3);
24136   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24137
24138   SDValue Flags;
24139
24140   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24141   if (Flags.getNode()) {
24142     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24143     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24144                        Flags);
24145   }
24146
24147   return SDValue();
24148 }
24149
24150 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24151                                                          SelectionDAG &DAG) {
24152   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24153   // optimize away operation when it's from a constant.
24154   //
24155   // The general transformation is:
24156   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24157   //       AND(VECTOR_CMP(x,y), constant2)
24158   //    constant2 = UNARYOP(constant)
24159
24160   // Early exit if this isn't a vector operation, the operand of the
24161   // unary operation isn't a bitwise AND, or if the sizes of the operations
24162   // aren't the same.
24163   EVT VT = N->getValueType(0);
24164   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24165       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24166       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24167     return SDValue();
24168
24169   // Now check that the other operand of the AND is a constant. We could
24170   // make the transformation for non-constant splats as well, but it's unclear
24171   // that would be a benefit as it would not eliminate any operations, just
24172   // perform one more step in scalar code before moving to the vector unit.
24173   if (BuildVectorSDNode *BV =
24174           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24175     // Bail out if the vector isn't a constant.
24176     if (!BV->isConstant())
24177       return SDValue();
24178
24179     // Everything checks out. Build up the new and improved node.
24180     SDLoc DL(N);
24181     EVT IntVT = BV->getValueType(0);
24182     // Create a new constant of the appropriate type for the transformed
24183     // DAG.
24184     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24185     // The AND node needs bitcasts to/from an integer vector type around it.
24186     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24187     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24188                                  N->getOperand(0)->getOperand(0), MaskConst);
24189     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24190     return Res;
24191   }
24192
24193   return SDValue();
24194 }
24195
24196 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24197                                         const X86Subtarget *Subtarget) {
24198   // First try to optimize away the conversion entirely when it's
24199   // conditionally from a constant. Vectors only.
24200   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24201   if (Res != SDValue())
24202     return Res;
24203
24204   // Now move on to more general possibilities.
24205   SDValue Op0 = N->getOperand(0);
24206   EVT InVT = Op0->getValueType(0);
24207
24208   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24209   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24210     SDLoc dl(N);
24211     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24212     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24213     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24214   }
24215
24216   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24217   // a 32-bit target where SSE doesn't support i64->FP operations.
24218   if (Op0.getOpcode() == ISD::LOAD) {
24219     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24220     EVT VT = Ld->getValueType(0);
24221
24222     // This transformation is not supported if the result type is f16
24223     if (N->getValueType(0) == MVT::f16)
24224       return SDValue();
24225
24226     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24227         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24228         !Subtarget->is64Bit() && VT == MVT::i64) {
24229       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24230           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24231       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24232       return FILDChain;
24233     }
24234   }
24235   return SDValue();
24236 }
24237
24238 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24239 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24240                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24241   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24242   // the result is either zero or one (depending on the input carry bit).
24243   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24244   if (X86::isZeroNode(N->getOperand(0)) &&
24245       X86::isZeroNode(N->getOperand(1)) &&
24246       // We don't have a good way to replace an EFLAGS use, so only do this when
24247       // dead right now.
24248       SDValue(N, 1).use_empty()) {
24249     SDLoc DL(N);
24250     EVT VT = N->getValueType(0);
24251     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24252     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24253                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24254                                            DAG.getConstant(X86::COND_B, DL,
24255                                                            MVT::i8),
24256                                            N->getOperand(2)),
24257                                DAG.getConstant(1, DL, VT));
24258     return DCI.CombineTo(N, Res1, CarryOut);
24259   }
24260
24261   return SDValue();
24262 }
24263
24264 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24265 //      (add Y, (setne X, 0)) -> sbb -1, Y
24266 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24267 //      (sub (setne X, 0), Y) -> adc -1, Y
24268 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24269   SDLoc DL(N);
24270
24271   // Look through ZExts.
24272   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24273   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24274     return SDValue();
24275
24276   SDValue SetCC = Ext.getOperand(0);
24277   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24278     return SDValue();
24279
24280   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24281   if (CC != X86::COND_E && CC != X86::COND_NE)
24282     return SDValue();
24283
24284   SDValue Cmp = SetCC.getOperand(1);
24285   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24286       !X86::isZeroNode(Cmp.getOperand(1)) ||
24287       !Cmp.getOperand(0).getValueType().isInteger())
24288     return SDValue();
24289
24290   SDValue CmpOp0 = Cmp.getOperand(0);
24291   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24292                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24293
24294   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24295   if (CC == X86::COND_NE)
24296     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24297                        DL, OtherVal.getValueType(), OtherVal,
24298                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24299                        NewCmp);
24300   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24301                      DL, OtherVal.getValueType(), OtherVal,
24302                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24303 }
24304
24305 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24306 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24307                                  const X86Subtarget *Subtarget) {
24308   EVT VT = N->getValueType(0);
24309   SDValue Op0 = N->getOperand(0);
24310   SDValue Op1 = N->getOperand(1);
24311
24312   // Try to synthesize horizontal adds from adds of shuffles.
24313   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24314        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24315       isHorizontalBinOp(Op0, Op1, true))
24316     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24317
24318   return OptimizeConditionalInDecrement(N, DAG);
24319 }
24320
24321 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24322                                  const X86Subtarget *Subtarget) {
24323   SDValue Op0 = N->getOperand(0);
24324   SDValue Op1 = N->getOperand(1);
24325
24326   // X86 can't encode an immediate LHS of a sub. See if we can push the
24327   // negation into a preceding instruction.
24328   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24329     // If the RHS of the sub is a XOR with one use and a constant, invert the
24330     // immediate. Then add one to the LHS of the sub so we can turn
24331     // X-Y -> X+~Y+1, saving one register.
24332     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24333         isa<ConstantSDNode>(Op1.getOperand(1))) {
24334       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24335       EVT VT = Op0.getValueType();
24336       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24337                                    Op1.getOperand(0),
24338                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24339       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24340                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24341     }
24342   }
24343
24344   // Try to synthesize horizontal adds from adds of shuffles.
24345   EVT VT = N->getValueType(0);
24346   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24347        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24348       isHorizontalBinOp(Op0, Op1, true))
24349     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24350
24351   return OptimizeConditionalInDecrement(N, DAG);
24352 }
24353
24354 /// performVZEXTCombine - Performs build vector combines
24355 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24356                                    TargetLowering::DAGCombinerInfo &DCI,
24357                                    const X86Subtarget *Subtarget) {
24358   SDLoc DL(N);
24359   MVT VT = N->getSimpleValueType(0);
24360   SDValue Op = N->getOperand(0);
24361   MVT OpVT = Op.getSimpleValueType();
24362   MVT OpEltVT = OpVT.getVectorElementType();
24363   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24364
24365   // (vzext (bitcast (vzext (x)) -> (vzext x)
24366   SDValue V = Op;
24367   while (V.getOpcode() == ISD::BITCAST)
24368     V = V.getOperand(0);
24369
24370   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24371     MVT InnerVT = V.getSimpleValueType();
24372     MVT InnerEltVT = InnerVT.getVectorElementType();
24373
24374     // If the element sizes match exactly, we can just do one larger vzext. This
24375     // is always an exact type match as vzext operates on integer types.
24376     if (OpEltVT == InnerEltVT) {
24377       assert(OpVT == InnerVT && "Types must match for vzext!");
24378       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24379     }
24380
24381     // The only other way we can combine them is if only a single element of the
24382     // inner vzext is used in the input to the outer vzext.
24383     if (InnerEltVT.getSizeInBits() < InputBits)
24384       return SDValue();
24385
24386     // In this case, the inner vzext is completely dead because we're going to
24387     // only look at bits inside of the low element. Just do the outer vzext on
24388     // a bitcast of the input to the inner.
24389     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24390                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24391   }
24392
24393   // Check if we can bypass extracting and re-inserting an element of an input
24394   // vector. Essentialy:
24395   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24396   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24397       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24398       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24399     SDValue ExtractedV = V.getOperand(0);
24400     SDValue OrigV = ExtractedV.getOperand(0);
24401     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24402       if (ExtractIdx->getZExtValue() == 0) {
24403         MVT OrigVT = OrigV.getSimpleValueType();
24404         // Extract a subvector if necessary...
24405         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24406           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24407           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24408                                     OrigVT.getVectorNumElements() / Ratio);
24409           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24410                               DAG.getIntPtrConstant(0, DL));
24411         }
24412         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24413         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24414       }
24415   }
24416
24417   return SDValue();
24418 }
24419
24420 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24421                                              DAGCombinerInfo &DCI) const {
24422   SelectionDAG &DAG = DCI.DAG;
24423   switch (N->getOpcode()) {
24424   default: break;
24425   case ISD::EXTRACT_VECTOR_ELT:
24426     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24427   case ISD::VSELECT:
24428   case ISD::SELECT:
24429   case X86ISD::SHRUNKBLEND:
24430     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24431   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24432   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24433   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24434   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24435   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24436   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24437   case ISD::SHL:
24438   case ISD::SRA:
24439   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24440   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24441   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24442   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24443   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24444   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24445   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24446   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24447   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24448   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24449   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24450   case X86ISD::FXOR:
24451   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24452   case X86ISD::FMIN:
24453   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24454   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24455   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24456   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24457   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24458   case ISD::ANY_EXTEND:
24459   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24460   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24461   case ISD::SIGN_EXTEND_INREG:
24462     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24463   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24464   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24465   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24466   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24467   case X86ISD::SHUFP:       // Handle all target specific shuffles
24468   case X86ISD::PALIGNR:
24469   case X86ISD::UNPCKH:
24470   case X86ISD::UNPCKL:
24471   case X86ISD::MOVHLPS:
24472   case X86ISD::MOVLHPS:
24473   case X86ISD::PSHUFB:
24474   case X86ISD::PSHUFD:
24475   case X86ISD::PSHUFHW:
24476   case X86ISD::PSHUFLW:
24477   case X86ISD::MOVSS:
24478   case X86ISD::MOVSD:
24479   case X86ISD::VPERMILPI:
24480   case X86ISD::VPERM2X128:
24481   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24482   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24483   case ISD::INTRINSIC_WO_CHAIN:
24484     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24485   case X86ISD::INSERTPS: {
24486     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24487       return PerformINSERTPSCombine(N, DAG, Subtarget);
24488     break;
24489   }
24490   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24491   }
24492
24493   return SDValue();
24494 }
24495
24496 /// isTypeDesirableForOp - Return true if the target has native support for
24497 /// the specified value type and it is 'desirable' to use the type for the
24498 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24499 /// instruction encodings are longer and some i16 instructions are slow.
24500 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24501   if (!isTypeLegal(VT))
24502     return false;
24503   if (VT != MVT::i16)
24504     return true;
24505
24506   switch (Opc) {
24507   default:
24508     return true;
24509   case ISD::LOAD:
24510   case ISD::SIGN_EXTEND:
24511   case ISD::ZERO_EXTEND:
24512   case ISD::ANY_EXTEND:
24513   case ISD::SHL:
24514   case ISD::SRL:
24515   case ISD::SUB:
24516   case ISD::ADD:
24517   case ISD::MUL:
24518   case ISD::AND:
24519   case ISD::OR:
24520   case ISD::XOR:
24521     return false;
24522   }
24523 }
24524
24525 /// IsDesirableToPromoteOp - This method query the target whether it is
24526 /// beneficial for dag combiner to promote the specified node. If true, it
24527 /// should return the desired promotion type by reference.
24528 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24529   EVT VT = Op.getValueType();
24530   if (VT != MVT::i16)
24531     return false;
24532
24533   bool Promote = false;
24534   bool Commute = false;
24535   switch (Op.getOpcode()) {
24536   default: break;
24537   case ISD::LOAD: {
24538     LoadSDNode *LD = cast<LoadSDNode>(Op);
24539     // If the non-extending load has a single use and it's not live out, then it
24540     // might be folded.
24541     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24542                                                      Op.hasOneUse()*/) {
24543       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24544              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24545         // The only case where we'd want to promote LOAD (rather then it being
24546         // promoted as an operand is when it's only use is liveout.
24547         if (UI->getOpcode() != ISD::CopyToReg)
24548           return false;
24549       }
24550     }
24551     Promote = true;
24552     break;
24553   }
24554   case ISD::SIGN_EXTEND:
24555   case ISD::ZERO_EXTEND:
24556   case ISD::ANY_EXTEND:
24557     Promote = true;
24558     break;
24559   case ISD::SHL:
24560   case ISD::SRL: {
24561     SDValue N0 = Op.getOperand(0);
24562     // Look out for (store (shl (load), x)).
24563     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24564       return false;
24565     Promote = true;
24566     break;
24567   }
24568   case ISD::ADD:
24569   case ISD::MUL:
24570   case ISD::AND:
24571   case ISD::OR:
24572   case ISD::XOR:
24573     Commute = true;
24574     // fallthrough
24575   case ISD::SUB: {
24576     SDValue N0 = Op.getOperand(0);
24577     SDValue N1 = Op.getOperand(1);
24578     if (!Commute && MayFoldLoad(N1))
24579       return false;
24580     // Avoid disabling potential load folding opportunities.
24581     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24582       return false;
24583     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24584       return false;
24585     Promote = true;
24586   }
24587   }
24588
24589   PVT = MVT::i32;
24590   return Promote;
24591 }
24592
24593 //===----------------------------------------------------------------------===//
24594 //                           X86 Inline Assembly Support
24595 //===----------------------------------------------------------------------===//
24596
24597 // Helper to match a string separated by whitespace.
24598 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24599   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24600
24601   for (StringRef Piece : Pieces) {
24602     if (!S.startswith(Piece)) // Check if the piece matches.
24603       return false;
24604
24605     S = S.substr(Piece.size());
24606     StringRef::size_type Pos = S.find_first_not_of(" \t");
24607     if (Pos == 0) // We matched a prefix.
24608       return false;
24609
24610     S = S.substr(Pos);
24611   }
24612
24613   return S.empty();
24614 }
24615
24616 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24617
24618   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24619     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24620         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24621         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24622
24623       if (AsmPieces.size() == 3)
24624         return true;
24625       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24626         return true;
24627     }
24628   }
24629   return false;
24630 }
24631
24632 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24633   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24634
24635   std::string AsmStr = IA->getAsmString();
24636
24637   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24638   if (!Ty || Ty->getBitWidth() % 16 != 0)
24639     return false;
24640
24641   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24642   SmallVector<StringRef, 4> AsmPieces;
24643   SplitString(AsmStr, AsmPieces, ";\n");
24644
24645   switch (AsmPieces.size()) {
24646   default: return false;
24647   case 1:
24648     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24649     // we will turn this bswap into something that will be lowered to logical
24650     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24651     // lower so don't worry about this.
24652     // bswap $0
24653     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24654         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24655         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24656         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24657         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24658         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24659       // No need to check constraints, nothing other than the equivalent of
24660       // "=r,0" would be valid here.
24661       return IntrinsicLowering::LowerToByteSwap(CI);
24662     }
24663
24664     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24665     if (CI->getType()->isIntegerTy(16) &&
24666         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24667         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24668          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24669       AsmPieces.clear();
24670       const std::string &ConstraintsStr = IA->getConstraintString();
24671       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24672       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24673       if (clobbersFlagRegisters(AsmPieces))
24674         return IntrinsicLowering::LowerToByteSwap(CI);
24675     }
24676     break;
24677   case 3:
24678     if (CI->getType()->isIntegerTy(32) &&
24679         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24680         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24681         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24682         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24683       AsmPieces.clear();
24684       const std::string &ConstraintsStr = IA->getConstraintString();
24685       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24686       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24687       if (clobbersFlagRegisters(AsmPieces))
24688         return IntrinsicLowering::LowerToByteSwap(CI);
24689     }
24690
24691     if (CI->getType()->isIntegerTy(64)) {
24692       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24693       if (Constraints.size() >= 2 &&
24694           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24695           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24696         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24697         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24698             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24699             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24700           return IntrinsicLowering::LowerToByteSwap(CI);
24701       }
24702     }
24703     break;
24704   }
24705   return false;
24706 }
24707
24708 /// getConstraintType - Given a constraint letter, return the type of
24709 /// constraint it is for this target.
24710 X86TargetLowering::ConstraintType
24711 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24712   if (Constraint.size() == 1) {
24713     switch (Constraint[0]) {
24714     case 'R':
24715     case 'q':
24716     case 'Q':
24717     case 'f':
24718     case 't':
24719     case 'u':
24720     case 'y':
24721     case 'x':
24722     case 'Y':
24723     case 'l':
24724       return C_RegisterClass;
24725     case 'a':
24726     case 'b':
24727     case 'c':
24728     case 'd':
24729     case 'S':
24730     case 'D':
24731     case 'A':
24732       return C_Register;
24733     case 'I':
24734     case 'J':
24735     case 'K':
24736     case 'L':
24737     case 'M':
24738     case 'N':
24739     case 'G':
24740     case 'C':
24741     case 'e':
24742     case 'Z':
24743       return C_Other;
24744     default:
24745       break;
24746     }
24747   }
24748   return TargetLowering::getConstraintType(Constraint);
24749 }
24750
24751 /// Examine constraint type and operand type and determine a weight value.
24752 /// This object must already have been set up with the operand type
24753 /// and the current alternative constraint selected.
24754 TargetLowering::ConstraintWeight
24755   X86TargetLowering::getSingleConstraintMatchWeight(
24756     AsmOperandInfo &info, const char *constraint) const {
24757   ConstraintWeight weight = CW_Invalid;
24758   Value *CallOperandVal = info.CallOperandVal;
24759     // If we don't have a value, we can't do a match,
24760     // but allow it at the lowest weight.
24761   if (!CallOperandVal)
24762     return CW_Default;
24763   Type *type = CallOperandVal->getType();
24764   // Look at the constraint type.
24765   switch (*constraint) {
24766   default:
24767     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24768   case 'R':
24769   case 'q':
24770   case 'Q':
24771   case 'a':
24772   case 'b':
24773   case 'c':
24774   case 'd':
24775   case 'S':
24776   case 'D':
24777   case 'A':
24778     if (CallOperandVal->getType()->isIntegerTy())
24779       weight = CW_SpecificReg;
24780     break;
24781   case 'f':
24782   case 't':
24783   case 'u':
24784     if (type->isFloatingPointTy())
24785       weight = CW_SpecificReg;
24786     break;
24787   case 'y':
24788     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24789       weight = CW_SpecificReg;
24790     break;
24791   case 'x':
24792   case 'Y':
24793     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24794         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24795       weight = CW_Register;
24796     break;
24797   case 'I':
24798     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24799       if (C->getZExtValue() <= 31)
24800         weight = CW_Constant;
24801     }
24802     break;
24803   case 'J':
24804     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24805       if (C->getZExtValue() <= 63)
24806         weight = CW_Constant;
24807     }
24808     break;
24809   case 'K':
24810     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24811       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24812         weight = CW_Constant;
24813     }
24814     break;
24815   case 'L':
24816     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24817       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24818         weight = CW_Constant;
24819     }
24820     break;
24821   case 'M':
24822     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24823       if (C->getZExtValue() <= 3)
24824         weight = CW_Constant;
24825     }
24826     break;
24827   case 'N':
24828     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24829       if (C->getZExtValue() <= 0xff)
24830         weight = CW_Constant;
24831     }
24832     break;
24833   case 'G':
24834   case 'C':
24835     if (isa<ConstantFP>(CallOperandVal)) {
24836       weight = CW_Constant;
24837     }
24838     break;
24839   case 'e':
24840     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24841       if ((C->getSExtValue() >= -0x80000000LL) &&
24842           (C->getSExtValue() <= 0x7fffffffLL))
24843         weight = CW_Constant;
24844     }
24845     break;
24846   case 'Z':
24847     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24848       if (C->getZExtValue() <= 0xffffffff)
24849         weight = CW_Constant;
24850     }
24851     break;
24852   }
24853   return weight;
24854 }
24855
24856 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24857 /// with another that has more specific requirements based on the type of the
24858 /// corresponding operand.
24859 const char *X86TargetLowering::
24860 LowerXConstraint(EVT ConstraintVT) const {
24861   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24862   // 'f' like normal targets.
24863   if (ConstraintVT.isFloatingPoint()) {
24864     if (Subtarget->hasSSE2())
24865       return "Y";
24866     if (Subtarget->hasSSE1())
24867       return "x";
24868   }
24869
24870   return TargetLowering::LowerXConstraint(ConstraintVT);
24871 }
24872
24873 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24874 /// vector.  If it is invalid, don't add anything to Ops.
24875 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24876                                                      std::string &Constraint,
24877                                                      std::vector<SDValue>&Ops,
24878                                                      SelectionDAG &DAG) const {
24879   SDValue Result;
24880
24881   // Only support length 1 constraints for now.
24882   if (Constraint.length() > 1) return;
24883
24884   char ConstraintLetter = Constraint[0];
24885   switch (ConstraintLetter) {
24886   default: break;
24887   case 'I':
24888     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24889       if (C->getZExtValue() <= 31) {
24890         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24891                                        Op.getValueType());
24892         break;
24893       }
24894     }
24895     return;
24896   case 'J':
24897     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24898       if (C->getZExtValue() <= 63) {
24899         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24900                                        Op.getValueType());
24901         break;
24902       }
24903     }
24904     return;
24905   case 'K':
24906     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24907       if (isInt<8>(C->getSExtValue())) {
24908         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24909                                        Op.getValueType());
24910         break;
24911       }
24912     }
24913     return;
24914   case 'L':
24915     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24916       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24917           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24918         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24919                                        Op.getValueType());
24920         break;
24921       }
24922     }
24923     return;
24924   case 'M':
24925     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24926       if (C->getZExtValue() <= 3) {
24927         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24928                                        Op.getValueType());
24929         break;
24930       }
24931     }
24932     return;
24933   case 'N':
24934     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24935       if (C->getZExtValue() <= 255) {
24936         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24937                                        Op.getValueType());
24938         break;
24939       }
24940     }
24941     return;
24942   case 'O':
24943     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24944       if (C->getZExtValue() <= 127) {
24945         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24946                                        Op.getValueType());
24947         break;
24948       }
24949     }
24950     return;
24951   case 'e': {
24952     // 32-bit signed value
24953     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24954       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24955                                            C->getSExtValue())) {
24956         // Widen to 64 bits here to get it sign extended.
24957         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24958         break;
24959       }
24960     // FIXME gcc accepts some relocatable values here too, but only in certain
24961     // memory models; it's complicated.
24962     }
24963     return;
24964   }
24965   case 'Z': {
24966     // 32-bit unsigned value
24967     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24968       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24969                                            C->getZExtValue())) {
24970         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24971                                        Op.getValueType());
24972         break;
24973       }
24974     }
24975     // FIXME gcc accepts some relocatable values here too, but only in certain
24976     // memory models; it's complicated.
24977     return;
24978   }
24979   case 'i': {
24980     // Literal immediates are always ok.
24981     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24982       // Widen to 64 bits here to get it sign extended.
24983       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24984       break;
24985     }
24986
24987     // In any sort of PIC mode addresses need to be computed at runtime by
24988     // adding in a register or some sort of table lookup.  These can't
24989     // be used as immediates.
24990     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24991       return;
24992
24993     // If we are in non-pic codegen mode, we allow the address of a global (with
24994     // an optional displacement) to be used with 'i'.
24995     GlobalAddressSDNode *GA = nullptr;
24996     int64_t Offset = 0;
24997
24998     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24999     while (1) {
25000       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25001         Offset += GA->getOffset();
25002         break;
25003       } else if (Op.getOpcode() == ISD::ADD) {
25004         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25005           Offset += C->getZExtValue();
25006           Op = Op.getOperand(0);
25007           continue;
25008         }
25009       } else if (Op.getOpcode() == ISD::SUB) {
25010         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25011           Offset += -C->getZExtValue();
25012           Op = Op.getOperand(0);
25013           continue;
25014         }
25015       }
25016
25017       // Otherwise, this isn't something we can handle, reject it.
25018       return;
25019     }
25020
25021     const GlobalValue *GV = GA->getGlobal();
25022     // If we require an extra load to get this address, as in PIC mode, we
25023     // can't accept it.
25024     if (isGlobalStubReference(
25025             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25026       return;
25027
25028     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25029                                         GA->getValueType(0), Offset);
25030     break;
25031   }
25032   }
25033
25034   if (Result.getNode()) {
25035     Ops.push_back(Result);
25036     return;
25037   }
25038   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25039 }
25040
25041 std::pair<unsigned, const TargetRegisterClass *>
25042 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25043                                                 const std::string &Constraint,
25044                                                 MVT VT) const {
25045   // First, see if this is a constraint that directly corresponds to an LLVM
25046   // register class.
25047   if (Constraint.size() == 1) {
25048     // GCC Constraint Letters
25049     switch (Constraint[0]) {
25050     default: break;
25051       // TODO: Slight differences here in allocation order and leaving
25052       // RIP in the class. Do they matter any more here than they do
25053       // in the normal allocation?
25054     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25055       if (Subtarget->is64Bit()) {
25056         if (VT == MVT::i32 || VT == MVT::f32)
25057           return std::make_pair(0U, &X86::GR32RegClass);
25058         if (VT == MVT::i16)
25059           return std::make_pair(0U, &X86::GR16RegClass);
25060         if (VT == MVT::i8 || VT == MVT::i1)
25061           return std::make_pair(0U, &X86::GR8RegClass);
25062         if (VT == MVT::i64 || VT == MVT::f64)
25063           return std::make_pair(0U, &X86::GR64RegClass);
25064         break;
25065       }
25066       // 32-bit fallthrough
25067     case 'Q':   // Q_REGS
25068       if (VT == MVT::i32 || VT == MVT::f32)
25069         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25070       if (VT == MVT::i16)
25071         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25072       if (VT == MVT::i8 || VT == MVT::i1)
25073         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25074       if (VT == MVT::i64)
25075         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25076       break;
25077     case 'r':   // GENERAL_REGS
25078     case 'l':   // INDEX_REGS
25079       if (VT == MVT::i8 || VT == MVT::i1)
25080         return std::make_pair(0U, &X86::GR8RegClass);
25081       if (VT == MVT::i16)
25082         return std::make_pair(0U, &X86::GR16RegClass);
25083       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25084         return std::make_pair(0U, &X86::GR32RegClass);
25085       return std::make_pair(0U, &X86::GR64RegClass);
25086     case 'R':   // LEGACY_REGS
25087       if (VT == MVT::i8 || VT == MVT::i1)
25088         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25089       if (VT == MVT::i16)
25090         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25091       if (VT == MVT::i32 || !Subtarget->is64Bit())
25092         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25093       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25094     case 'f':  // FP Stack registers.
25095       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25096       // value to the correct fpstack register class.
25097       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25098         return std::make_pair(0U, &X86::RFP32RegClass);
25099       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25100         return std::make_pair(0U, &X86::RFP64RegClass);
25101       return std::make_pair(0U, &X86::RFP80RegClass);
25102     case 'y':   // MMX_REGS if MMX allowed.
25103       if (!Subtarget->hasMMX()) break;
25104       return std::make_pair(0U, &X86::VR64RegClass);
25105     case 'Y':   // SSE_REGS if SSE2 allowed
25106       if (!Subtarget->hasSSE2()) break;
25107       // FALL THROUGH.
25108     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25109       if (!Subtarget->hasSSE1()) break;
25110
25111       switch (VT.SimpleTy) {
25112       default: break;
25113       // Scalar SSE types.
25114       case MVT::f32:
25115       case MVT::i32:
25116         return std::make_pair(0U, &X86::FR32RegClass);
25117       case MVT::f64:
25118       case MVT::i64:
25119         return std::make_pair(0U, &X86::FR64RegClass);
25120       // Vector types.
25121       case MVT::v16i8:
25122       case MVT::v8i16:
25123       case MVT::v4i32:
25124       case MVT::v2i64:
25125       case MVT::v4f32:
25126       case MVT::v2f64:
25127         return std::make_pair(0U, &X86::VR128RegClass);
25128       // AVX types.
25129       case MVT::v32i8:
25130       case MVT::v16i16:
25131       case MVT::v8i32:
25132       case MVT::v4i64:
25133       case MVT::v8f32:
25134       case MVT::v4f64:
25135         return std::make_pair(0U, &X86::VR256RegClass);
25136       case MVT::v8f64:
25137       case MVT::v16f32:
25138       case MVT::v16i32:
25139       case MVT::v8i64:
25140         return std::make_pair(0U, &X86::VR512RegClass);
25141       }
25142       break;
25143     }
25144   }
25145
25146   // Use the default implementation in TargetLowering to convert the register
25147   // constraint into a member of a register class.
25148   std::pair<unsigned, const TargetRegisterClass*> Res;
25149   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25150
25151   // Not found as a standard register?
25152   if (!Res.second) {
25153     // Map st(0) -> st(7) -> ST0
25154     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25155         tolower(Constraint[1]) == 's' &&
25156         tolower(Constraint[2]) == 't' &&
25157         Constraint[3] == '(' &&
25158         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25159         Constraint[5] == ')' &&
25160         Constraint[6] == '}') {
25161
25162       Res.first = X86::FP0+Constraint[4]-'0';
25163       Res.second = &X86::RFP80RegClass;
25164       return Res;
25165     }
25166
25167     // GCC allows "st(0)" to be called just plain "st".
25168     if (StringRef("{st}").equals_lower(Constraint)) {
25169       Res.first = X86::FP0;
25170       Res.second = &X86::RFP80RegClass;
25171       return Res;
25172     }
25173
25174     // flags -> EFLAGS
25175     if (StringRef("{flags}").equals_lower(Constraint)) {
25176       Res.first = X86::EFLAGS;
25177       Res.second = &X86::CCRRegClass;
25178       return Res;
25179     }
25180
25181     // 'A' means EAX + EDX.
25182     if (Constraint == "A") {
25183       Res.first = X86::EAX;
25184       Res.second = &X86::GR32_ADRegClass;
25185       return Res;
25186     }
25187     return Res;
25188   }
25189
25190   // Otherwise, check to see if this is a register class of the wrong value
25191   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25192   // turn into {ax},{dx}.
25193   if (Res.second->hasType(VT))
25194     return Res;   // Correct type already, nothing to do.
25195
25196   // All of the single-register GCC register classes map their values onto
25197   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25198   // really want an 8-bit or 32-bit register, map to the appropriate register
25199   // class and return the appropriate register.
25200   if (Res.second == &X86::GR16RegClass) {
25201     if (VT == MVT::i8 || VT == MVT::i1) {
25202       unsigned DestReg = 0;
25203       switch (Res.first) {
25204       default: break;
25205       case X86::AX: DestReg = X86::AL; break;
25206       case X86::DX: DestReg = X86::DL; break;
25207       case X86::CX: DestReg = X86::CL; break;
25208       case X86::BX: DestReg = X86::BL; break;
25209       }
25210       if (DestReg) {
25211         Res.first = DestReg;
25212         Res.second = &X86::GR8RegClass;
25213       }
25214     } else if (VT == MVT::i32 || VT == MVT::f32) {
25215       unsigned DestReg = 0;
25216       switch (Res.first) {
25217       default: break;
25218       case X86::AX: DestReg = X86::EAX; break;
25219       case X86::DX: DestReg = X86::EDX; break;
25220       case X86::CX: DestReg = X86::ECX; break;
25221       case X86::BX: DestReg = X86::EBX; break;
25222       case X86::SI: DestReg = X86::ESI; break;
25223       case X86::DI: DestReg = X86::EDI; break;
25224       case X86::BP: DestReg = X86::EBP; break;
25225       case X86::SP: DestReg = X86::ESP; break;
25226       }
25227       if (DestReg) {
25228         Res.first = DestReg;
25229         Res.second = &X86::GR32RegClass;
25230       }
25231     } else if (VT == MVT::i64 || VT == MVT::f64) {
25232       unsigned DestReg = 0;
25233       switch (Res.first) {
25234       default: break;
25235       case X86::AX: DestReg = X86::RAX; break;
25236       case X86::DX: DestReg = X86::RDX; break;
25237       case X86::CX: DestReg = X86::RCX; break;
25238       case X86::BX: DestReg = X86::RBX; break;
25239       case X86::SI: DestReg = X86::RSI; break;
25240       case X86::DI: DestReg = X86::RDI; break;
25241       case X86::BP: DestReg = X86::RBP; break;
25242       case X86::SP: DestReg = X86::RSP; break;
25243       }
25244       if (DestReg) {
25245         Res.first = DestReg;
25246         Res.second = &X86::GR64RegClass;
25247       }
25248     }
25249   } else if (Res.second == &X86::FR32RegClass ||
25250              Res.second == &X86::FR64RegClass ||
25251              Res.second == &X86::VR128RegClass ||
25252              Res.second == &X86::VR256RegClass ||
25253              Res.second == &X86::FR32XRegClass ||
25254              Res.second == &X86::FR64XRegClass ||
25255              Res.second == &X86::VR128XRegClass ||
25256              Res.second == &X86::VR256XRegClass ||
25257              Res.second == &X86::VR512RegClass) {
25258     // Handle references to XMM physical registers that got mapped into the
25259     // wrong class.  This can happen with constraints like {xmm0} where the
25260     // target independent register mapper will just pick the first match it can
25261     // find, ignoring the required type.
25262
25263     if (VT == MVT::f32 || VT == MVT::i32)
25264       Res.second = &X86::FR32RegClass;
25265     else if (VT == MVT::f64 || VT == MVT::i64)
25266       Res.second = &X86::FR64RegClass;
25267     else if (X86::VR128RegClass.hasType(VT))
25268       Res.second = &X86::VR128RegClass;
25269     else if (X86::VR256RegClass.hasType(VT))
25270       Res.second = &X86::VR256RegClass;
25271     else if (X86::VR512RegClass.hasType(VT))
25272       Res.second = &X86::VR512RegClass;
25273   }
25274
25275   return Res;
25276 }
25277
25278 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25279                                             Type *Ty) const {
25280   // Scaling factors are not free at all.
25281   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25282   // will take 2 allocations in the out of order engine instead of 1
25283   // for plain addressing mode, i.e. inst (reg1).
25284   // E.g.,
25285   // vaddps (%rsi,%drx), %ymm0, %ymm1
25286   // Requires two allocations (one for the load, one for the computation)
25287   // whereas:
25288   // vaddps (%rsi), %ymm0, %ymm1
25289   // Requires just 1 allocation, i.e., freeing allocations for other operations
25290   // and having less micro operations to execute.
25291   //
25292   // For some X86 architectures, this is even worse because for instance for
25293   // stores, the complex addressing mode forces the instruction to use the
25294   // "load" ports instead of the dedicated "store" port.
25295   // E.g., on Haswell:
25296   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25297   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25298   if (isLegalAddressingMode(AM, Ty))
25299     // Scale represents reg2 * scale, thus account for 1
25300     // as soon as we use a second register.
25301     return AM.Scale != 0;
25302   return -1;
25303 }
25304
25305 bool X86TargetLowering::isTargetFTOL() const {
25306   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25307 }